2

I have a scenario where an album has many tracks and the tracks have the possibility to have featured artists, also know as artists. The associations are setup just fine but its mainly my view code that suffers from major verbosity:

<table>
  <% @album.tracks.each do |track| %>
    <td>
      <%= raw !track.artists.empty? ? "#{track.name} (feat. #{track.artists.map {|artist| link_to artist.name, artist_path(artist)}.to_sentence({:two_words_connector => ' & ', :last_word_connector => ' & '})})" : track.name %>
   </td>
<table>

The objective for the above is to display the name of the track and if the track has any featured artists (with the help of the to_sentence helper method), list them out and link to their own show view. A rendered example would look something like this:

Give It To Me (feat. Justin Timberlake & Nelly Furtado)

or if there's more than two featured artists:

Good Friday (feat. Common, Pusha T, Kid Cudi, Big Sean & Charlie Wilson)

Is there any way I could accomplish the following without writing such a long expression?

Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

1 Answers1

1

I would move all that logic into a helper, for example create a method application_helper.rb:

def display_track(track)
  if track.artists.empty? 
    track.name
  else
    links = track.artists.map {|artist| link_to artist.name, artist_path(artist) }
    sentence = links.to_sentence(two_words_connector: ' & ', last_word_connector: ' & ')

    "#{track.name} (feat. #{sentence})"    
  end
end

Then your view simplifies to:

<table>
  <% @album.tracks.each do |track| %>
    <td>
      <%= raw display_track(track) %>
    </td>
  <% end %>
<table>
infused
  • 24,000
  • 13
  • 68
  • 78
  • Thanks. Just remove `do` from the `map` code block and I'll mark this as correct. Otherwise you'd encounter an error. – Carl Edwards May 02 '15 at 11:57