instance method
capture
Ruby on Rails edge
Signature
capture(*, **, &block)
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
<%= 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> <%= @greeting %> </body> </html> “`
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” “`
Parameters
-
argsrest -
kwargskeyrest -
blockblock
Source
# File actionview/lib/action_view/helpers/capture_helper.rb, line 56
def capture(*, **, &block)
value = nil
@output_buffer ||= ActionView::OutputBuffer.new
buffer = @output_buffer.capture { value = yield(*, **) }
string = if @output_buffer.equal?(value)
buffer
else
buffer.presence || value
end
case string
when OutputBuffer
string.to_s
when ActiveSupport::SafeBuffer
string
when String
ERB::Util.html_escape(string)
end
end
Defined in actionview/lib/action_view/helpers/capture_helper.rb line 56
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::CaptureHelper