我正在寻找一个简单示例,说明如何使用 Ruby 和正则表达式模式匹配编写内部 DSL。类似于 Sinatra 处理路由的方式
get '/say/*/to/*' do
# Some Ruby code here
end
也类似于 Cucumber 处理步骤定义的方式:
Given /^I have (\d+) cucumbers in my belly$/ do |cukes|
# Some Ruby code here
end
我对构建器或流畅的方法链不感兴趣。基本上我想要一个看起来像这样的 Ruby 类:
class SpecVocabulary
match ‘pattern’ do
# Some Ruby code here
end
# Or, using a different keyword
phrase ‘pattern’ do
# Some Ruby code here
end
end
我正在苦苦挣扎的是连接代码,使 SpecVocabular 类自动匹配模式并填写它的数据。
我希望有人有一个简单的例子来说明如何做到这一点,我试图避免深入研究 Sinatra 和 Cucumber 的源代码。
顺便说一下,我已经有了自然语言定义,尽管我故意省略了它。
最佳答案
这是一篇关于在 Ruby 中创建 DSL 的综合博文:
http://www.daniel-azuma.com/blog/view/z3bqa0t01uugg1/implementing_dsl_blocks
顺便说一句,在类中使用 DSL 并不常见,我想它看起来更像是:
vocabulary :SpecVocabulary do
match 'pattern' do
# Some Ruby code here
end
# Or, using a different keyword
phrase 'pattern' do
# Some Ruby code here
end
end
关于ruby - 如何使用 Ruby + Regex 编写内部自然语言 DSL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4411244/