首页 > 解决方案 > 从markdown标签执行ruby代码

问题描述

我被要求测试我在降价文档(使用 Middleman 创建的网站)中提供的示例。

我需要测试我建议的 API 请求示例是否正确。

所以在我的例子中,我有:

_example.md

```ruby
uri = URI.parse("http://localhost:3000/oauth/token")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/x-www-form-urlencoded; charset=utf-8"
request.set_form_data(
  "client_id" => "id",
  "client_secret" => "secret",
  "grant_type" => "password",
  "password" => "password",
  "username" => "user@example.com"
)

req_options = {
  use_ssl: uri.scheme == "https"
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end
response.code
```

这个想法是输入mardown文件并```ruby ```在我的测试文件 test.rb中的标签之间读取

def run_http_request

  File.open('../_example.md').each_line do |line|
    next if line.start_with? '```'
    line
  end

end

我想要这个方法来执行http请求......

标签: rubymarkdownmiddleman

解决方案


尝试以下操作:

content = File.read('../_example.md')
matches = content.match(/```ruby(.+)```/m)

code = matches[1] # matches[0] contains the code and the ```ruby``` part
eval(code)

希望能帮助到你!


推荐阅读