Ruby:如何使用hash作为方法的参数

时间:2015-02-11 02:20:21

标签: ruby-on-rails ruby

我想在Rails中定义一个帮助器:

# Usage:
# selector_link('This is New', tab: 'new')
# selector_link('This is like sorter', sort: 'like_count')
# selector_link('This is number 7', number: 7)
def selector_link2(link_text, param_name: param_content)
  link_to link_text, url_for(param_name: param_content), class: ('active'if params[:param_name] == param_content)
  # Should Generate:
  # link_to link_text, url_for(tab: 'new'), class: ('active'if params[:tab] == 'new')
  # link_to link_text, url_for(sort: 'like_count'), class: ('active'if params[:sort] == 'like_count')
  # link_to link_text, url_for(number: 7), class: ('active'if params[:number] == 7)
end

问题是,我不知道如何让key url_for(key: path)接受输入hash's key,而params[:key]似乎也是无效的语法。

这种方法的正确方法是什么?

更新: 这就是我最终的结果

def selector_link2(link_text, link = {})
  key = link.first[0]
  value = link.first[1]
  link_to link_text, url_for(link), class: ('active'if params[link[key].to_s] == link[value])
end

1 个答案:

答案 0 :(得分:2)

它被称为命名参数或keyword argument,因此

def x(a, b: 'test')
  puts "a = #{a}"
  puts "b = #{b}"
end

可以称为:

x 123, b: 'yay'
# a = 123
# b = yay

你也可以这样打字:

def x(a, b: nil) 
  b ||= anything      
end

编辑1 :所以在你的情况下(如果我没有被误解),它应该是这样的:

def selector_link(link_text, tab: path)
  link_to link_text, url_for(key: tab), class: ('active' if tab == 'new')
end

编辑2:或类似的东西:

def selector_link(link_text, opt={})
  link_to link_text, url_for(opt), class: ('active' if opt[:tab] == 'new')
end

这两个功能都可以称为selector_link('a',tab:'new')

编辑3 为您的上一个问题编辑,它应该是这样的:

def selector_link(link_text, opt={})
  active = nil
  active = 'active' if !opt[:tab].nil? and opt[:tab] == 'new'
  active = 'active' if !opt[:sort].nil? and opt[:sort] == 'like_count' 
  link_to link_text, url_for(opt), class: active
end 

编辑4 如果Rail的助手可以访问params,您可以这样输入:

def selector_link(link_text, opt={})
  key = opt.first[0] # get the first :key or :param_name
  link_to link_text, url_for(opt), class: ('active' if opt[key].to_s == params[key].to_s)
end 

# call it using:
selector_link('This is New', tab: 'new')
selector_link('This is like sorter', sort: 'like_count')
selector_link('This is number 7', number: 7)

如果无法从帮助程序访问params,则必须手动传递:

def selector_link(link_text, params, opt={})
  key = opt.first[0]
  link_to link_text, url_for(opt), class: ('active' if opt[key].to_s == params[key].to_s)
end 

# call it using:
selector_link('This is New', params, tab: 'new')
selector_link('This is like sorter', params, sort: 'like_count')
selector_link('This is number 7', params, number: 7)

编辑5 上次更新,重复部分

def selector_link2(link_text, link = {})
  key, value = link.first
  link_to link_text, url_for(link), class: ('active' if params[key].to_s == value.to_s)
end