如何找到私有的单例方法

10

我定义了一个称为 Vehicle 的模块,就像这样:

module Vehicle
  class <<self
    def build
    end

    private

    def background
    end
  end
end

调用Vehicle.singleton_methods将返回[:build]

我如何检查Vehicle定义的所有私有单例方法?

1个回答

10

在 Ruby 1.9+ 中,您可以简单地执行:

Vehicle.singleton_class.private_instance_methods(false)
#=> [:background]
在 Ruby 1.8 中,情况会更加复杂。
Vehicle.private_methods
#=> [:background, :included, :extended, :method_added, :method_removed, ...]

将返回所有私有方法。您可以通过执行以下操作来过滤大多数在外部声明的方法:

Vehicle.private_methods - Module.private_methods
#=> [:background, :append_features, :extend_object, :module_function]

但是那样不能完全清除它们,你需要创建一个模块来完成这个任务

Vehicle.private_methods - Module.new.private_methods
#=> [:background]

这个最后一个不幸的要求是必须创建一个模块然后扔掉它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接