我想用 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 助手不一致。第二种更好,但并不理想,因为现在我需要明确检查我不支持的关键字参数,否则可能会无提示地失败。我是否遗漏了什么,或者是第二种方法?
最佳答案
从 Ruby 2.1 开始,您甚至可以使用 Binding#local_variable_get 访问名为 class
的关键字参数像这样:
def special_link_tag(body, url, class: 'special')
"class = " + binding.local_variable_get(:class)
end
关于ruby-on-rails - 如何使用 `class` 作为关键字参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30984658/