给定以下帮助程序方法。
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
def link_tags(collection)
collection.split(',').map do |tag|
link_to tag, tag_filter_post_path(tag)
end.join(', ')
end
使用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
试试这个(按照 xnm 的建议使用 link_to
):
def link_tags(collection)
collection.split(',').each {|tag| link_to tag, tag_filter_post_path(tag)}.join(', ')
end
对于代码重构 http://refactormycode.com 是一个不错的选择
这是 Ruby 部分:
http://refactormycode.com/codes/recent/ruby