Ruby on rails 我如何重构这个方法?
给定以下帮助器方法Ruby on rails 我如何重构这个方法?,ruby-on-rails,ruby,refactoring,Ruby On Rails,Ruby,Refactoring,给定以下帮助器方法 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) )
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
使用
join
而不是专门处理最后一个元素(除非元素是唯一的,否则它也不会像您这样工作),然后在后面进行连接。对每个的调用也是多余的
def link_tags(collection)
tags = collection.split(',')
tags.map do |tag|
content_tag(:a, tag, href: tags_filter_post_path(tag))
end.join(', ')
end
使用
join
而不是专门处理最后一个元素(除非元素是唯一的,否则它也不会像您这样工作),然后在后面进行连接。对每个的调用也是多余的
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的建议,使用链接到):
尝试此操作(按照xnm的建议,使用链接到):
对于代码,重新分解是一个很好的选择
这是Ruby部分:
对于代码,重新分解是一个很好的选择
这是Ruby部分:
为什么要在
map
上调用每个?代码审阅问题属于上一页。@JörgWMittag谢谢,我不知道CodeReview.SE;)为什么要在map
上调用每个?代码审阅问题属于上一页。@JörgWMittag谢谢,我不知道CodeReview.SE;)没想到把它改成一个链接到
-nice(+1)。我决定保留标记
变量,因为我觉得它有助于为正在发生的事情添加一些上下文,但显然这都是主观的。在我看来,这是最好的一个。我只想用.collect
切换.map
,因为我觉得这样更有意义PI同意.collect
更清晰,尽管我看到.map
使用得更频繁,而且是每个Ruby程序员都应该知道的一种方法。谢谢,我已经用最终结果更新了我的帖子。我没想到要将它改为链接到-nice(+1)。我决定保留标记
变量,因为我觉得它有助于为正在发生的事情添加一些上下文,但显然这都是主观的。在我看来,这是最好的一个。我只想用.collect
切换.map
,因为我觉得这样更有意义PI同意.collect
更清晰,尽管我看到.map
使用得更多,而且是每个Ruby程序员都应该知道的一种方法。谢谢,我已经用最终结果更新了我的帖子。输出:`,作为文本,而不是我希望的链接。使用.reduce(:输出:`,作为文本,而不是我希望的链接。使用.reduce(:谢谢,我不知道那个网站!;)@KleberS。很高兴它能帮上忙谢谢,我不知道那个网站!;)@KleberS。很高兴它能帮上忙
def link_tags(collection)
collection.split(',').map do |tag|
link_to tag, tag_filter_post_path(tag)
end.join(', ')
end
def link_tags(collection)
collection.split(',').each {|tag| link_to tag, tag_filter_post_path(tag)}.join(', ')
end