开发者

How to write an internal, natural language, DSL using Ruby + Regex?

I’m looking for a simple example of how to write an internal DSL using Ruby and regex pattern matching. Similar to how Sinatra handles routes

get '/say/*/to/*' do
   # Some Ruby code here
end
开发者_StackOverflow社区

Also similar to how Cucumber handles step definitions:

Given /^I have (\d+) cucumbers in my belly$/ do |cukes|
   # Some Ruby code here
end

I’m not interested in builders, or fluent method chaining. Basically I want a Ruby class which looks something like this:

class SpecVocabulary

   match ‘pattern’ do
      # Some Ruby code here
   end

   # Or, using a different keyword
   phrase ‘pattern’ do
      # Some Ruby code here
   end
end

What I’m struggling with is wiring-up the code which makes the SpecVocabular class automatically match patterns and fill out it’s data.

I’m hoping someone has a simple example of how to do this, I’m trying to avoid having to dive in the source for Sinatra and Cucumber.

Incidentally I already have the natural language define, though I omitted it purposely.


Here's a comprehensive blog post on creating DSLs in Ruby:

http://www.daniel-azuma.com/blog/view/z3bqa0t01uugg1/implementing_dsl_blocks

BTW, it is not common to use your DSL within a class, I guess it would rather look like:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜