Search code examples
rubyblockdsl

DSL block without argument in ruby


I'm writing a simple dsl in ruby. Few weeks ago I stumbled upon some blog post, which show how to transform code like:

some_method argument do |book|
  book.some_method_on_book
  book.some_other_method_on_book :with => argument
end

into cleaner code:

some_method argument do
   some_method_on_book
   some_other_method_on_book :with => argument
end

I can't remember how to do this and I'm not sure about downsides but cleaner syntax is tempting. Does anyone have a clue about this transformation?


Solution

  • def some_method argument, &blk
      #...
      book.instance_eval &blk
      #...
    end
    

    UPDATE: However, that omits book but don't let you use the argument. To use it transparently you must transport it someway. I suggest to do it on book itself:

    class Book
      attr_accessor :argument
    end
    
    def some_method argument, &blk
      #...
      book.argument = argument
      book.instance_eval &blk
      #...
    end
    
    some_method 'argument' do
       some_method_on_book
       some_other_method_on_book argument
    end