选择性地将选项传递给另一个方法

时间:2009-10-30 02:29:26

标签: ruby-on-rails ruby

我有一个方法song_link在内部调用link_to。我希望调用者能够将选项哈希传递给song_link,然后使用与其相关的选项,并将其余部分传递给link_to。这是我的代码:

  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

即,我想查看options[:primary_only]是否存在,以及是否确实将其用于song_link目的而未将其传递给link_to

显然,这种方法无法扩展,因为我添加了与song_link相关但与link_to无关的更多选项。我该怎么做?

2 个答案:

答案 0 :(得分:6)

简化帮助:

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

利用nilfalse一样好的事实,其他一切都与true一样好。

答案 1 :(得分:1)

在传递之前,从哈希中删除您自己处理的任何选项。