如何使用Ruby + Regex编写内部自然语言DSL?

时间:2010-12-10 16:50:51

标签: ruby regex nlp dsl

我正在寻找一个如何使用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

我正在努力的是连接代码,使SpecVocabulary类自动匹配模式并填写它的数据。

我希望有人有一个如何做到这一点的简单例子,我试图避免不得不潜入Sinatra和Cucumber的来源。

顺便说一下,我已经定义了自然语言,但我故意省略它。

1 个答案:

答案 0 :(得分:1)

这是一篇关于在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