How does profitability magic work in ActionView?

I was watching how content_for works, and watching block.callin a method capture_erb_with_buffer. Apparently, he magically writes a buffer variable, which is then truncated. However, I believe that this is not recommended, and you can just call <%=yield :tag%>now. How it works? If I call profitability from an ERB template, where does it give?

It would be very helpful to evaluate a simple code example to illustrate this point.

+3
source share
3 answers

This little tiny method, called executein ActionView::Base, explains it all. http://google.com/codesearch/p?hl=en#m8Vht-lU3vE/vendor/rails/actionpack/lib/action_view/base.rb&q=capture_helper.rb&d=5&l=337

  def execute(template)
    send(template.method, template.locals) do |*names|
      instance_variable_get "@content_for_#{names.first || 'layout'}"
    end
  end

A block do |*names|... endis one that receives yield. You will notice that it @content_for_#{names.first}matches the variable set in the process content_for.

He called from AV :: TemplateHandlers :: Compilable in #render, and I would suggest other places.

  def render(template)
    @view.send :execute, template
  end

http://google.com/codesearch/p?hl=en#m8Vht-lU3vE/vendor/rails/actionpack/lib/action_view/template_handlers/compilable.rb&q=execute&exact_package=git://github.com/payalgupta/todo- list.git & sa = N & cd = 17 & ct = rc & l = 28

+2
source

, yield ERB, , .

layout.html.erb:

<html>
  <head>
    <title> <%= @title || 'Plain Title' %> </title>
    <%= yield :head %>
  </head>
<body>
  <div id='menu'>
    <%= yield :menu %>
  </div>
  <div id='content'>
    <%= yield %>
  </div>
  <div id='footer'>
    <%= yield :footer %>
  </div>
</body>

4 (: head,: menu, footer default) @title.

, . , , @title .

:

<% @title = 'About' %>
<% content_for :menu do %>
  <%= link_to 'Back to Home', :action => :home %>
<% end %>

We rock!

<% content_for :footer do %>
  An Illinois based company.
<% end %>

""

<% @title = 'Edit' %>
<% content_for :head do %>
  <style type='text/css'> .edit_form div {display:inline-block;} </style>
<% end %>

<% form_for :thing, :html => {:class => 'edit_form'} do |f| %>
   ...
<% end %>

, , , content_for :something, yield :something .

, content_for: something, content_for.

+4

Simply:

call income in the method executes the code that was passed to the method through the block.

for instance

def my_method
  yield
end

my_method { puts "Hello" }
my_method { puts "World" }

these 5 lines will display the following output

Hello
World

See the next page for a pleasant discussion of profitability in Ruby: Ruby Yield

-1
source

Source: https://habr.com/ru/post/1740938/


All Articles