在 Rails Helper 中为其他作用域方法创建作用域块
我想在块帮助器中定义一些帮助器方法,但将它们保留在块的范围内,以便我可以拥有合理的方法名称并且看起来更干净。
假设我想要执行以下操作(一个非常基本的示例),在我看来,使用助手:
<%= foo_box do |b| %>
<%= b.title( 'Foo Bar' ) %>
Lorem Ipsum...
<% end %>
要生成类似
<div class="foo_box">
<h2>Foo Bar</h2>
Lorem Ipsum...
</div>
这样的内容,我还可以有一个 bar_box
块助手,它也可以有一个 title
方法输出完全不同的东西。
目前,我将它们实现为不同的方法,例如 foo_box
和 foo_box_title
,用 foo_box
处理块,如下所示:
def foo_box(&block)
content_tag(:div, capture(&block), :class => 'foo_box')
end
I would like to define some helper methods within a block helper but keep them within the scope of the block so that I can have sensible method names and it looks cleaner.
Say I want to do the following (a very basic example), in my view using helpers:
<%= foo_box do |b| %>
<%= b.title( 'Foo Bar' ) %>
Lorem Ipsum...
<% end %>
To produce something like
<div class="foo_box">
<h2>Foo Bar</h2>
Lorem Ipsum...
</div>
This way I could also have a bar_box
block helper which could also have a title
method which outputs something totally different.
Currently I have them implemented as different methods, e.g. foo_box
and foo_box_title
, with foo_box
handling the block like so:
def foo_box(&block)
content_tag(:div, capture(&block), :class => 'foo_box')
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从表面上看,
capture
不允许您将任何参数传递到您想要执行的块中。 (b
) 中的 bass 参数必须是您定义title
等方法的某种对象。因此,让我们定义一个帮助器类,它将输出您需要的内容,并将其传递给从视图传入的块,然后捕获它并将其包围在div
中,就像上面所做的那样。我会做这样的事情:看看我如何绕过捕获方法的限制?通过将新的 Proc 绑定到当前作用域,并在其中传递辅助对象,我们得到一个可以不带参数调用的块,因此可以被 capture 接受。另外,请确保您的帮助程序类包含
ActionView::Helpers
中的所有相关帮助程序方法。希望这有帮助!By the looks of it,
capture
doesn't let you pass any arguments into the block, which you want to do. The argument to bass in (b
) has to be an object of some sort that you define thetitle
etc. methods on. So, lets define a helper class which will output the stuff you need, and pass it to the block passed in from the view, and then capture it and surround it in thediv
as you did above. I would do something like this:See how I got around the limitation of the
capture
method? By binding a new Proc to the current scope, and passing in the helper object there, we get a block we can call with no arguments, and thus acceptable bycapture
. Also, make certain your helper class includes all the relevant helper methods fromActionView::Helpers
. Hope this helps!