Converting Rails 3 to Rails 2: helpers with blocks

一笑奈何 提交于 2019-12-06 04:46:05

问题


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 %>

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?

Thanks.


回答1:


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 %>



回答2:


This might not answer your question, but there is a much simpler way to achieve even/odd color table, using the cycle command

 @items = [1,2,3,4]
  <table>
  <% @items.each do |item| %>
    <tr class="<%= cycle("even", "odd") -%>">
      <td>item</td>
    </tr>
  <% end %>
  </table>

Hope this at introduces you to a cool Rails utility



来源:https://stackoverflow.com/questions/3630854/converting-rails-3-to-rails-2-helpers-with-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!