如何找到私有的singleton方法



我定义了一个类似的模块Vehicle

module Vehicle
  class <<self
    def build
    end
    private
    def background
    end
  end
end

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

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

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

Vehicle.singleton_class.private_instance_methods(false)
#=> [:background]

在Ruby1.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]

最后一个不幸的要求是创建一个模块却将其丢弃。

最新更新