Как я создаю помощника с блоком?

Иногда целесообразно проглотить исключение.

Для колокольчиков и пользовательского интерфейса запрос пользователя с сообщением об ошибке является прерывистым, и обычно ему вообще нечего делать. В этом случае я просто регистрирую это и имею дело с этим, когда оно появляется в журналах.

9
задан Mohsen Nosratinia 8 May 2015 в 14:10
поделиться

2 ответа

You should use CaptureHelper.

def my_div(some_options, &block)
  # capture the value of the block a string
  content = capture(&block)
  # concat the value to the output
  concat(content)
end

<% my_div([]) do %>
  <p>The content</p>
<% end %>


def my_div(some_options, &block)
  # capture the value of the block a string
  # and returns it. You MUST use <%= in your view.
  capture(&block)
end

<%= my_div([]) do %>
  <p>The content</p>
<% end %>

Use capture + concat if you need to concat the output. Use capture if you need to capture and then reuse the content. If your block doesn't explicitely use <%=, then you MUST call concat (preferred way).

This is an example of a method that hides the content if the user it not an admin.

def if_admin(options = {}, &block)
  if admin?
    concat content_tag(:div, capture(&block), options)
  end
end

<% if_admin(:style => "admin") do %>
<p>Super secret content.</p>
<% end %>
17
ответ дан 4 December 2019 в 11:43
поделиться

http://www.rubycentral.com/book/tut_containers.html

Оператор yield вернет результат переданного блока. Итак, если вы хотите напечатать (консоль?)

def my_div &block
  yield
end

my_div { puts "Something" } 

, вывести «Something»

Но: В чем идея вашего метода? Вывод DIV?

1
ответ дан 4 December 2019 в 11:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: