【问题标题】:Execute ruby code from markdown tag [closed]从markdown标签执行ruby代码[关闭]
【发布时间】:2018-04-25 14:35:30
【问题描述】:

我被要求测试我在 Markdown 文档(使用 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 请求...

【问题讨论】:

  • 好的,你已经描述了你想要做什么。你有什么问题?
  • 我需要方法 run_http_request 进行 API 调用 像这样没有执行任何操作...这里没有出现任何内容...我遗漏了一些东西,但我不知道它是什么(不是还是专家)

标签: ruby markdown middleman


【解决方案1】:

尝试以下方法:

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

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

希望对你有帮助!

【讨论】:

  • 太多了!你拯救了我的一天:)
  • 刚刚做到了 :) 对不起,我做到了
猜你喜欢
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2019-08-24
  • 2013-09-29
相关资源
最近更新 更多