Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DSL block without argument in ruby

Tags:

ruby

block

dsl

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?

like image 483
dhuCerbin Avatar asked Feb 10 '12 09:02

dhuCerbin


People also ask

How do you pass a block as argument in Ruby?

We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block ). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield .

What is code block in Ruby?

Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is always enclosed with braces or written between do.. end. The braces syntax always have the higher precedence over the do.. end syntax.


1 Answers

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
like image 90
Sony Santos Avatar answered Oct 04 '22 04:10

Sony Santos