Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rails yield to multiple block in the erb templates?

How does rails get away with the following in an .erb file?

<%= yield :sidebar %>
<%= yield :other_bar %>
<%= yield :footer %>

How are they able to yield multiple times in the same context to different symbols? Is this some kind of rails magic?

I'm totally familiar with:

def some_method(arg1, arg2, &block)
 yield(:block)
end

To my knowledge following doesn't work:

def some_incorrect_method(arg1, &block1, &block2)
 yield(:block1)
 yield(:block2)
end

So how are they doing it? How do they make it work?

like image 768
haroldcampbell Avatar asked Dec 03 '22 04:12

haroldcampbell


1 Answers

They are passing a symbol into yield...

yield :symbol

...not yielding to a different block.

It works more like this:

def some_method(arg1, arg2, &block)
  yield(:some_symbol1)
  yield(:some_symbol2)
end

some_method do |symbol|
  case symbol
  when :some_symbol1
     # do A
  when :some_symbol2
     # do B
  else
     # unrecognised symbol?
  end
end
like image 79
Mike Tunnicliffe Avatar answered Mar 01 '23 22:03

Mike Tunnicliffe