views:

50

answers:

2

I have a method song_link that calls link_to internally. I want the caller to be able to pass an options hash to song_link, which will then use the options relevant to it, and pass the rest to link_to. Here's my code:

  def song_link(song, separator = nil, options = {})
    if separator.class == Hash
      options = separator
      separator = nil # not sure about this logic either!
                      # I guess I should roll it into the options hash
    end

    primary_only = false
    if options[:primary_only]
      options.delete(:primary_only)
      primary_only = true
    end

    link_to title_with_artists(song, separator, primary_only), song_path(:song_slug => song.song_slug, :artist_slug => song.artist_slug), options
  end

I.e., I want to check to see whether options[:primary_only] exists, and if it does use it for song_link's purposes without passing it along to link_to

Obviously this approach won't scale as I add more options that are relevant for song_link but not for link_to. How should I do this?

+1  A: 

Remove whatever options you process yourself from the hash before passing it along.

Azeem.Butt
So basically do what I'm doing?
Horace Loeb
It's either that or pass two different options hashes.
Azeem.Butt
+5  A: 

Simplify the helper:

def song_link(song, options = {})
  separator    = options.delete(:separator)
  primary_only = options.delete(:primary_only)

  name = title_with_artists(song, separator, primary_only)
  path = song_path(:song_slug => song.song_slug, :artist_slug => song.artist_slug)
  link_to name, path, options
end

Take advantage of the fact that nil is just as good as false and everything else is as good as true.

Ryan McGeary