如何使用`class`作为关键字参数?

时间:2015-06-22 16:02:23

标签: ruby-on-rails ruby

我想用class关键字参数编写Rails助手,如下所示:

special_link_tag body, url, class: 'special'

我无法引用class关键字,因为class是保留字:

def special_link_tag body, url, class: 'special'
  class ||= 'whatever' # error! 'class' is reserved
  :etc
end

我看到两个选项:

def special_link_tag(body, url, klass: 'special')
  klass ||= 'whatever'
  :etc
end

def special_link_tag(body, url, **options)
  klass = options[:class]
  klass ||= 'whatever'
  :etc
end

我不喜欢他们。第一个与Rails助手不一致。第二个更好,但不理想,因为现在我需要明确检查关键字参数我不支持或冒险失败的风险。我错过了什么,或者是第二种方法可以去这里?

2 个答案:

答案 0 :(得分:5)

这是一个保留字,因此您不能将其用作变量,方法或参数名称,与iffor等其他名称相同。

而不是我同意的klass是俗气的,为什么不更具体:

def special_link_tag(body, url, css_class: 'special')
  css_class ||= 'whatever'
end

你可以毫无问题地使用哈希样式的参数,所以如果你真的设置了class: '...'的方法调用,那么你可能想要使用那些而不是关键字参数样式的定义。

def special_link_tag(body, url, options = nil)
  options ||= { }
  options[:class] ||= 'whatever'
end

答案 1 :(得分:4)

从Ruby 2.1开始,您甚至可以使用Binding#local_variable_get访问名为class的关键字参数,如下所示:

def special_link_tag(body, url, class: 'special')
  "class = " + binding.local_variable_get(:class)
end