繁体   English   中英

如何获得Ruby类中未定义方法的列表?

[英]How can one get the list of undefined methods in a Ruby class?

在玩Ruby的同时,我编写了以下代码:

class A
end

A.singleton_class.instance_eval do
    undef_method :new
end

# or
# class << B
#   undef_method :new
# end

A.new

> NoMethodError: undefined method `new' for A:Class
>         from (irb):8
>         from /home/mmsequeira/.rvm/rubies/ruby-1.9.3-p327/bin/irb:16:in `<main>'

这很酷。 但是我如何知道给定类中未定义哪些方法?

默认情况下不能。 取消定义方法会将其从存在中删除。 但是,您可以在删除它们时记录它们。 这可以通过方法挂钩来完成,以捕获所有内容并避免丑陋的别名方法链接:

class Module
  def method_undefined name
    (@undefined_methods ||= []) << name
  end

  def singleton_method_undefined name
    (@undefined_methods ||= []) << name
  end

  def undefined_methods
    @undefined_methods || []
  end
end

这将捕获通过undef_methodundef未定义的方法:

class C
  def foo; end
  def bar; end

  undef foo
  undef_method :bar
end

C.undefined_methods  #=> [:foo, :bar]
C.singleton_class.instance_eval { undef new }
C.singleton_class.undefined_methods  #=> [:new]

当然,必须先在模块中包含hook方法,然后才能捕获任何内容。

也许您需要重新定义Module#undef_method

class Module
  alias original_undef_method :undef_method
  @@undef_methods = {}
  def undef_method *methods
    methods.each{|method| @@undef_methods[[self, method]] ||= true}
    original_undef_method(*methods)
  end
  def self.undef_methods; @@undef_methods.keys end
end

然后,您得到:

class A
end
A.singleton_class.instance_eval do
    undef_method :new
end
Module.undef_methods
# => [[#<Class:A>, :new]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM