capture(*args) public

The capture method extracts part of a template as a String object. You can then use this object anywhere in your templates, layout, or helpers.

The capture method can be used in ERB templates…

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

…and Builder (RXML) templates.

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

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

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

The return of capture is the string generated by the block. For Example:

@greeting # => "Welcome to my shiny new web page! The date and time is 2018-09-06 11:09:16 -0500"
Show source
Register or log in to add new notes.
February 22, 2011
7 thanks

Passing arguments to block

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)

Then simply…

 <%= export(@a, @b) do |my_custom_var| %>
  <% if my_custom_var.nil? %>
    My custom var is nil!!!
  <% end %>
<% end %>
September 16, 2012
This note might be spam Show