在 Ruby 中为 new 使用正确数量的参数
我正在开发一种可以使用不同版本的 Gherkin 的 gem,但我遇到了一个问题: 在 2.4.0 版本中,Gherkin::Formatter::Model::Scenario.new 需要 6 个参数,但在 2.6.5 中,它需要 7 个参数。
所以我的问题是这种情况下的最佳实践是什么?我应该这样做:
case Gherkin::Version
when '2.4.0'
do the init with 6 arguments
else
with the 7
end
我也在考虑创建一个 new_with_arity 方法:
class Object
def new_with_arity(*params)
puts method(:initialize).arity # => -1
puts method(:new).arity # => -1
new(*(params + [nil] * (params.count - method(:new).arity)))
end
end
但是这不起作用,new 和initialize 的arity 是-1。 你有主意吗?
I am working on a gem that can uses different version of Gherkin, but I'm facing a problem:
in the 2.4.0 version Gherkin::Formatter::Model::Scenario.new takes 6 arguments but in 2.6.5 it takes 7 arguments.
So my question is what is a best practice in this case ? Should I do:
case Gherkin::Version
when '2.4.0'
do the init with 6 arguments
else
with the 7
end
I was thinking also of creating a new_with_arity method:
class Object
def new_with_arity(*params)
puts method(:initialize).arity # => -1
puts method(:new).arity # => -1
new(*(params + [nil] * (params.count - method(:new).arity)))
end
end
However this does not work, the arity of new and initialize is -1.
Do you have an idea ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议遵循吉姆·德维尔的建议。说这是一个非常有趣的想法,而且你已经非常接近了。问题是如果没有实例就无法获取该方法,因此技巧是首先使用分配。
I would recommend following Jim Deville's advice. Saying that it's quite an interesting idea and you were pretty close. The problem is you can't get the method without having an instance, so the trick is to use allocate first.
我会构建 2 个 Gherkin 适配器,并为正确的版本加载正确的适配器。或者,您正在使用 Rubygems,因此您可以强制使用特定版本的 Gherkin 解析器
I would build 2 Gherkin adapters and load up the proper one for the proper version. Or, you are using Rubygems, so you can force a specific version of the Gherkin parser