给出以下辅助方法。
def link_tags(collection)
tags = collection.split(',')
tags.map.each do |tag|
if tag == tags.last
content_tag(:a, tag, href: tags_filter_post_path(tag) )
else
content_tag(:a, tag, href: tags_filter_post_path(tag) ) + ', '
end
end.reduce(:<<)
end
我怎么能对此做一点重构?
编辑:重构后的最终代码建议。
def link_tags(collection)
collection.split(',').collect do |tag|
link = ""
link += link_to tag, tags_filter_post_path(tag)
end.join(', ').html_safe
end
答案 0 :(得分:5)
def link_tags(collection)
collection.split(',').map do |tag|
link_to tag, tag_filter_post_path(tag)
end.join(', ')
end
答案 1 :(得分:1)
使用join
而不是特意处理最后一个元素(除非元素是唯一的,否则也不会按照你的方式工作),然后再连接。对each
的调用也是多余的。
def link_tags(collection)
tags = collection.split(',')
tags.map do |tag|
content_tag(:a, tag, href: tags_filter_post_path(tag))
end.join(', ')
end
答案 2 :(得分:0)
尝试此操作(xnm建议使用link_to
):
def link_tags(collection)
collection.split(',').each {|tag| link_to tag, tag_filter_post_path(tag)}.join(', ')
end
答案 3 :(得分:0)