将Rails 3转换为Rails 2:带块的帮助器 [英] Converting Rails 3 to Rails 2: helpers with blocks
问题描述
在Rails 3中,我使用以下帮助程序来获得颜色奇数的表:
In Rails 3 I use the following helper in order to get a even-odd-coloured table:
def bicolor_table(collection, classes = [], &block)
string = ""
even = 0
for item in collection
string << content_tag(:tr, :class => (((even % 2 == 0) ? "even " : "odd ") + classes.join(" "))) do
yield(item)
end
even = 1 - even
end
return string
end
我在这样的视图中使用它:
And I use it in my views like this:
<%= bicolor_table(services) do |service| %>
<td><%= image_tag service.area.small_image %></td>
<td><%= link_to service.title, service %></td>
<% end %>
现在,我必须将应用程序迁移到Rails2.问题是Rails 2不使用Erubis,因此,当它找到<%= what%>标签时,它仅调用what.to_s.因此,就我而言,这导致尝试执行
Now, I have to migrate the application to Rails 2. The problem is Rails 2 doesn't use Erubis, so when it finds a <%= whatever %> tag, it just calls whatever.to_s. So, in my case, this result in trying to execute
(bicolor_table(services) do |service|).to_s
具有明显的(不良的)后果.问题是:我原则上是错的吗(例如助手不应该这样工作,而要使用…")还是应该寻找解决方法?
With the obvious (bad) consequences. The question is: am I wrong in principle (like "helpers shouldn't work this way, use instead …") or should I look for a workaround?
谢谢.
推荐答案
这是完全可行的,并且实际上使某些类型的助手变得更加简单.您需要使用<% %>
和concat
来实现.
This is totally doable, and in fact makes certain types of helpers much simpler. You need to use <% %>
and concat
to achieve this.
def my_block_helper(param, &block)
output = %(<div class="wrapper-markup">#{ capture(&block) }</div>)
concat output
end
像这样在您的视图中使用它:
use it in your views like this:
<% my_block_helper do %>
<span>Some Content</span>
<% end %>
这篇关于将Rails 3转换为Rails 2:带块的帮助器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!