views:

39

answers:

1

I a writing a DSL to generate parsers for bioinformatics flat files. I would like to let the user define helper functions in block and then include the function in the parsing context object. I would like to use a syntax like:

rules = Rules.new do
  helpers do
     def foo()
       #...
     end
     def bar( baz )
       #...
     end
   end
   # Here come the parsing rules which can access both helper methods
 end

I would like to add the helper methods to a module definition and the include the module in a instance (just the instance not the class).

Do you have an idea how I can reach that goal ? Answers with a slightly different syntax are appreciated too.

+1  A: 

Something like this, perhaps?

class Rules
  def initialize(&block)
    instance_eval &block
  end

  def helpers
    yield
  end
end

Rules.new do
  helpers do
    def hi_world
      puts "Hello World!"
    end
  end

  hi_world
end

Note though that here the helpers method does nothing special, it just relies on the fact that the Rules block is already the current scope.

Ciarán Walsh