0

次のヘルパーメソッドが与えられます。

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
4

4 に答える 4

5
def link_tags(collection)
  collection.split(',').map do |tag| 
    link_to tag, tag_filter_post_path(tag)
  end.join(', ')
end
于 2012-06-06T03:18:41.470 に答える
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
于 2012-06-06T03:17:30.360 に答える
0

これを試してください(link_toxnmによって提案されたように):

def link_tags(collection)
  collection.split(',').each {|tag| link_to tag, tag_filter_post_path(tag)}.join(', ')
end
于 2012-06-06T03:21:18.377 に答える
0

コードのリファクタリングには、 http://refactormycode.comが適切なオプションです。

これはRubyセクションです。

http://refactormycode.com/codes/recent/ruby

于 2012-06-06T05:05:33.750 に答える