ruby - 从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请求......
解决方案
尝试以下操作:
content = File.read('../_example.md')
matches = content.match(/```ruby(.+)```/m)
code = matches[1] # matches[0] contains the code and the ```ruby``` part
eval(code)
希望能帮助到你!
推荐阅读
- alfresco - 在露天检测自定义用户操作
- android - android.security.KeyStoreException:签名/MAC 验证失败尝试在 React Native 模块中解密时
- javascript - 获取每个对象的键并将该数据插入数组
- ios - 包裹在 UIViewRepresentable 中的 UITextView 不显示复制/粘贴菜单
- java - Maven Eclipse 插件、WAR 覆盖以及对项目与 Maven 存储库的依赖关系
- python - 如何在没有 Anaconda/Spyder 的情况下查看使用 NetworkX 库创建的图表?
- xslt - 根据 ID 值对记录进行排序
- java - Java递归函数:仅添加具有特定属性的元素
- java - 通过成员注解获取外部类
- c# - Blazor:HttpContext.RequestServices 提供与 IServiceProvider 不同的范围实例