带预定义关键字参数的define_method [英] define_method with predefined keyword arguments

查看:109
本文介绍了带预定义关键字参数的define_method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个采用关键字参数的方法.当不提供关键字参数时,我想提高它,我可以自己编写代码-但理想情况下,我想让Ruby为我做.我也希望能够使用Method#parameters检查新定义的方法.如果我使用简写的双连字符(如**kwargs),则我期望的实际结构对parameters是不可见的.

I want to define a method that takes keyword arguments. I would like it to raise when keyword arguments are not provided, and I can code this myself - but ideally I would like to let Ruby do that for me. Also I would like to be able to inspect the freshly defined method using Method#parameters. If I use a shorthand double-splat (like **kwargs) the actual structure I expect is not visible to parameters.

我当然可以这样做:

define_method(:foo) do | foo:, bar: |
  # ...
end

可达到预期效果:

method(:foo).parameters
# => [[:keyreq, :foo], [:keyreq, :bar]]

但是我不能以编程方式传递这些参数,必须将它们逐字地放置在代码中.有没有办法可以绕过这个?

but I cannot pass those arguments programmatically, they have to be literally placed in the code. Is there a way I could bypass this?

推荐答案

您必须使用eval动态定义参数(而不仅仅是关键字参数),例如使用 class_eval :

You have to use eval to define arguments dynamically (not just keyword arguments), e.g. using class_eval:

class MyClass
  name = :foo
  args = [:bar, :baz]
  class_eval <<-METHOD, __FILE__, __LINE__ + 1
    def #{name}(#{args.map { |a| "#{a}:" }.join(', ')}) # def foo(bar:, baz:)
      [#{args.join(', ')}]                              #   [bar, baz]
    end                                                 # end
  METHOD
end

MyClass.new.foo(bar: 1, baz: 2)
#=> [1, 2]

MyClass.instance_method(:foo).parameters
#=> [[:keyreq, :bar], [:keyreq, :baz]]

这篇关于带预定义关键字参数的define_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆