Tom Lehman
Tom Lehman

Reputation: 89203

Selectively pass options to another method

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?

Upvotes: 1

Views: 216

Answers (2)

Ryan McGeary
Ryan McGeary

Reputation: 239895

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.

Upvotes: 6

Azeem.Butt
Azeem.Butt

Reputation: 5861

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

Upvotes: 1

Related Questions