views:

53

answers:

2

This is a helper method I found in the ruby on rails application spree commerce.

I'm trying to better understand what's going on here, particularly with the capture() method on line 12, which I've never seen before. If there is a block given, it captures it, otherwise there is no content. But where does capture() come from? what is it doing?

 11   def hook(hook_name, locals = {}, &block)
 12     content = block_given? ? capture(&block) : ''
 13     result = Spree::ThemeSupport::Hook.render_hook(hook_name, content, self, locals)
 14     block_given? ? concat(result.to_s) : result
 15   end
+1  A: 

the capture block lets you take a block from a template file, process it and store it in a variable.

API: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#M002300

What it appears is going on here, is you call the hook method on a block in a template, that is processed and then formatted based upon the theme within spree (based on the name of the modules) and then spits out (or to be more techinical, returns) the newly formatted block.

Geoff Lanotte
+2  A: 

When you yield from a block in an ERB view (at least in rails 1.x and 2.x), it will write directly to the buffer and hence to the rendered html, which is probably not desired. Instead you can 'capture' the result of the evaluation of the block and assign it to a variable as they've done here. Anyway, I am probably not explaining it as well as Ryan Bates does here:

http://railscasts.com/episodes/40-blocks-in-view

rainkinz