[LRUG] Funny gotcha with blocks in partials.

Tim Cowlishaw tim at timcowlishaw.co.uk
Mon Jun 22 08:31:09 PDT 2009


Hey chaps.

I've come across a strange issue writing helpers that take a block  
argument, that i was wondering if someone might be able to shed some  
light on? Basically, what happens is this:

I have a helper, called array_to_list - which take an n-dimensional  
array, and turns into an n-level nested html <ul>. It also takes an  
optional block argument that formats the content of each <li>:

   def array_to_list(data, opts={}, array=nil, &block)
     array ||= data #pass the top level data structure down the stack.
     if data.is_a?(Array)
       content_tag(:ul, data.map{ |e| content_tag(:li,  
array_to_list(e, opts, array, &block)) }.join , opts)
     else
       block ? block.call(data, array) : data
     end
   end


So, this works exactly as expected when i pass it a pure ruby block  
argument:

<%= array_to_list(@flash_games, :class => "flash_games_grid") do | 
game, array|
         link_to(game_path(:id => game.id,  
image_tag(game.image_url(:grid), :alt => 'A Game'. :width =>  
128, :height => 128))
  %>

However, if i pass it a block that contains ERB template strings, it  
breaks - it just returns the result of each call to the block direct  
to the template being rendered, as it's executed, rather than  
returning it as the result of the call to array_to_list itself:

<% array_to_list(@flash_games, :class => "flash_games_grid") do |game,  
array| %>
         <a href="<%= game_path(:id => game.id) %>"><img src="<%=  
game.image_url(:grid) %>" alt="A Game" width="128" height="128" /></a>
<% end %>

I have a suspicion that this is something the rails capture() method  
might be needed for, but i'm struggling to understand how, Anyone seen  
anything similar in the past?

Cheers,

Tim



More information about the Chat mailing list