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

时间:2020-12-15 20:51:32

I want to write Rails helpers with a class keyword argument, like so:

我想用类关键字参数编写Rails helper,如下:

special_link_tag body, url, class: 'special'

I can't refer to the class keyword because class is a reserved word:

我不能引用class关键字,因为class是一个保留词:

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

I see two options:

我看到两个选择:

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

I like neither of them. The first is inconsistent with Rails helpers. The second is better, but not ideal because now I need to explicitly check for keyword arguments I don't support or risk failing silently. Am I missing anything, or is the second method the way to go here?

他们两个我都不喜欢。第一个与Rails helper不一致。第二个更好,但不理想,因为现在我需要显式地检查我不支持的关键字参数,否则可能会不小心失败。我是否遗漏了什么,或者是第二种方法?

2 个解决方案

#1


2  

Since Ruby 2.1 you can access even a keyword argument named class with Binding#local_variable_get like so:

由于Ruby 2.1,您甚至可以使用绑定#local_variable_get来访问名为类的关键字参数:

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

#2


5  

It's a reserved word, so you cannot use it as a variable, a method or argument name, same as others like if or for.

它是一个保留字,所以不能将它用作变量、方法或参数名,就像if或for那样。

Instead of klass, which I agree is tacky, why not be more specific:

我同意klass很俗气,为什么不更具体一些呢?

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

You can use hash-style arguments without issue, so if you're really set on a method call with class: '...' then you might want to use those rather than a keyword-argument-style definition.

您可以毫无问题地使用hashstyle参数,因此如果您确实设置了带有类的方法调用:'…然后,你可能想要使用它们,而不是关键词辩论式的定义。

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

#1


2  

Since Ruby 2.1 you can access even a keyword argument named class with Binding#local_variable_get like so:

由于Ruby 2.1,您甚至可以使用绑定#local_variable_get来访问名为类的关键字参数:

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

#2


5  

It's a reserved word, so you cannot use it as a variable, a method or argument name, same as others like if or for.

它是一个保留字,所以不能将它用作变量、方法或参数名,就像if或for那样。

Instead of klass, which I agree is tacky, why not be more specific:

我同意klass很俗气,为什么不更具体一些呢?

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

You can use hash-style arguments without issue, so if you're really set on a method call with class: '...' then you might want to use those rather than a keyword-argument-style definition.

您可以毫无问题地使用hashstyle参数,因此如果您确实设置了带有类的方法调用:'…然后,你可能想要使用它们,而不是关键词辩论式的定义。

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