Create a scope block in the rails helper for additional methods

I would like to define some helper methods in the block helper, but keep them within the block so that I have reasonable method names and it looks cleaner.

Let's say I want to do the following (a very simple example), in my opinion, with helpers:

<%= foo_box do |b| %>
    <%= b.title( 'Foo Bar' ) %>
    Lorem Ipsum...
<% end %>

To create something like

<div class="foo_box">
   <h2>Foo Bar</h2>
   Lorem Ipsum...
</div>

That way, I could also have a helper block bar_box, which could also have a method titlethat outputs something completely different.

I am currently using them as different methods, for example. foo_boxand foo_box_title, while foo_boxprocessing the block as follows:

def foo_box(&block)
  content_tag(:div, capture(&block), :class => 'foo_box')
end
+3
source share
1 answer

, capture - , . (b) - , title .. , , , , , div, . - :

class FooBoxHelper
  include ActionView::Helpers::TagHelper  
  def title(text)
    content_tag(:h2, text)
  end
  def small(text)
    content_tag(:p, text, :class => "small")
  end
end

def foo_box(&block)

  new_block = Proc.new do 
    helper = FooBoxHelper.new
    block.call(helper)
  end
  content_tag(:div, capture(&new_block), :class => 'foo_box')
end

, capture? Proc , , , , capture. , , ActionView::Helpers. , !

+4

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


All Articles