简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM