method

capture

capture(*args)
public

The capture method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.

The capture method can be used in ERB templates…

<% @greeting = capture do %>
  Welcome to my shiny new web page!  The date and time is
  <%= Time.now %>
<% end %>

…and Builder (RXML) templates.

@timestamp = capture do
  "The current timestamp is #{Time.now}."
end

You can then use that variable anywhere else. For example:

<html>
<head><title><%= @greeting %></title></head>
<body>
<b><%= @greeting %></b>
</body></html>

2Notes

Passing arguments to block

stevo · Feb 22, 20117 thanks

To pass arguments to block being captured, just list them as capture method params. I.e.

def export(exportable, export_klass, options={}, &block)
result = ""
#...
if block_given?
  result += capture(my_custom_var_i_want_to_pass_to_block, &block)
end
result
end

Then simply...

<%= export(@a, @b) do |my_custom_var| %>

<% if my_custom_var.nil? %> My custom var is nil!!! <% end %> <% end %>

Coding test and analyzer @ DupCode

tommy_lam · Sep 15, 2012

We are soon launching DupCode.com, at which you can test and analyze your coding skills, compete with friends and at the same time pave the way to professional coder Come drop your email at DupCode.com and we will inform you the minute we launch!