0

I am reading the book Agile web developpment with rails 4. there is a part where the products' cart is showing only if it is not empty, my question is the function in the view send to the helper only 2 attributes while in the implementation there are 3 parameters.

in the view I have the bellow code, which render to _cart where I have the cart show

<%= hidden_div_if(@cart.line_items.empty?, id: 'cart') do %>
        <%= render @cart %>
<% end %>

the helper has:

module ApplicationHelper
def hidden_div_if(condition, attributes = {}, &block)
 if condition
  attributes["style"] = "display: none"
 end
 content_tag("div", attributes, &block) end
end

My question is the &block in this case receives id: 'cart' but is it a optional attibute? that why it comes with &. but what about attributes = {}? I am really not sure how that is happening, could someone explain me a bit?

Thanks!!

Moh
  • 249
  • 3
  • 15

1 Answers1

1

The code between and including do and end is the block, and this is the third argument for hidden_div_if, which is simply passed on to content_tag. The & in the definition of hidden_div_if captures the block in your view, whereas the & in the call to content_tag expands it again to pass it along.

The answer here explains this idea nicely with a few examples. I recommend testing everything out yourself in irb to get a feel for it.

Community
  • 1
  • 1
Jimeux
  • 2,956
  • 1
  • 18
  • 14