Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find private singleton methods

I have defined a module Vehicle like such

module Vehicle
  class <<self
    def build
    end

    private

    def background
    end
  end
end

A call to Vehicle.singleton_methods returns [:build].

How can I inspect all private singleton methods defined by Vehicle?

like image 325
Mike Bradford Avatar asked Aug 27 '12 02:08

Mike Bradford


1 Answers

In Ruby 1.9+, you can simply do:

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

In Ruby 1.8, things are a bit more complicated.

Vehicle.private_methods
#=> [:background, :included, :extended, :method_added, :method_removed, ...]

will return all private methods. You can filter most of the ones declared outside by doing

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

but that doesn't get quite all of them out, you have to create a module to do that

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

This last one has the unfortunate requirement of creating a module only to throw it away.

like image 160
Andrew Marshall Avatar answered Sep 20 '22 23:09

Andrew Marshall