开发者

Rails 3 refactoring issue

The following view code generates a series of links with totals (as expected):

<% @jobs.group_by(&:employer_name).sort.each do |employer, jobs| %>
    <%= link_to开发者_运维知识库 employer, jobs_path() %> <%= "(#{jobs.length})" %>
<% end %>

However, when I refactor the view's code and move the logic to a helper, the code doesn't work as expect.

view:

<%= employer_filter(@jobs_clone) %>

helper:

def employer_filter(jobs)
    jobs.group_by(&:employer_name).sort.each do |employer,jobs|
        link_to employer, jobs_path()
    end   
end

The following output is generated:

<Job:0x10342e628>#<Job:0x10342e588>#<Job:0x10342e2e0>Employer A#<Job:0x10342e1c8>Employer B#<Job:0x10342e0d8>Employer C#<Job:0x10342ded0>Employer D#

What am I not understanding? At first blush, the code seems to be equivalent.


In the first example, it is directly outputting to erb, in the second example it is returning the result of that method.

Try this:

def employer_filter(jobs)
    employer_filter = ""
    jobs.group_by(&:employer_name).sort.each do |employer,jobs|
        employer_filter += link_to(employer, jobs_path())
    end   
    employer_filter
end

Then call it like this in the view:

raw(employer_filter(jobs))

Also note the use of "raw". Once you move generation of a string out of the template you need to tell rails that you don't want it html escaped.

For extra credit, you could use the "inject" command instead of explicitly building the string, but I am lazy and wanted to give you what I know would work w/o testing.


This syntax worked as I hoped it would:

def employer_filter(jobs_clone)
    jobs_clone.group_by(&:employer_name).sort.collect { |group,items|
        link_to( group, jobs_path() ) + " (#{items.length})"
    }.join(' | ').html_safe
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜