Comma seperated list of links in rails

One very common requirement of web applications is to have a comma-separated list of links display in the browser (usually things like categories or tags). This is traditionally quite annoying for programmers because the usual approach is to iterate through an enumerable object and build up a string, then deal with the messy business of shaving off that inevitable “last comma” so your links don’t end up looking like this;

Games, Movies, Videos,

As always, such things are much easier in ruby. In the case of a rails application, if you place the following code in your application helper file;

  def comma_seperated_links_for(list)

    raise TypeError, "parameter must be an array" unless list.is_a? Array 
    return if list.count == 0

    list.collect do |item| 
      raise TypeError, "items must respond to 'name'" unless last_item.respond_to? :name
      link_to(, url_for(item)) 
     end.join(", ").html_safe

You can lean that up by removing all of the “raise” calls, I only include them here to demonstrate the limitations of the implementation. Not only is this a slick and efficient implementation, it also means you get a huge dose of Knuthian readability straight into your views 🙂

   <%= comma_seperated_links_for @product.categories %>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s