在 Ruby 中为 new 使用正确数量的参数

发布于 2024-12-16 15:05:22 字数 607 浏览 4 评论 0原文

我正在开发一种可以使用不同版本的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

源来凯始玺欢你 2024-12-23 15:05:22

我建议遵循吉姆·德维尔的建议。说这是一个非常有趣的想法,而且你已经非常接近了。问题是如果没有实例就无法获取该方法,因此技巧是首先使用分配。

class Object
  def new_with_arity(*params)
    new *(params + [nil] * (allocate.method(:initialize).arity - params.size))
  end
end


class One
  def initialize a
    [a]
  end
end

class Two
  def initialize a, b
    [a, b]
  end
end

One.new_with_arity 1     #=> [1]
Two.new_with_arity 1, 2  #=> [1, 2]
Two.new_with_arity 1     #=> [1, nil]

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.

class Object
  def new_with_arity(*params)
    new *(params + [nil] * (allocate.method(:initialize).arity - params.size))
  end
end


class One
  def initialize a
    [a]
  end
end

class Two
  def initialize a, b
    [a, b]
  end
end

One.new_with_arity 1     #=> [1]
Two.new_with_arity 1, 2  #=> [1, 2]
Two.new_with_arity 1     #=> [1, nil]
我很坚强 2024-12-23 15:05:22

我会构建 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文