Using Ruby 2.2.1, How to list all methods (preferrably Array of String names) of a class that is only defined in that class / file where include
and extend
methods are filtered out. I want to distinguish class and instance methods as well.
Currently, I can get all the uninherited methods using MyClass.methods(false)
but this still includes methods that are part of an include
Module.
Explicitly, say, I have:
class MyClass < BaseClass
extend AnotherBaseClass
include MyModule
def foo
end
def bar
end
end
I want to get:
somecodethatreturnssomething
#=> ['foo', 'bar']
# Not including BaseClass, AnotherBaseClass, and ModuleClass methods
UPDATE:
@Wand Maker's answer is correct when I run it in a separate irb console. However, I still have a problem specifically that I am including ActionView::Helpers::UrlHelper
in MyClass
. I always get extra methods: default_url_options?
, default_url_options=
, and default_url_options
. I thought that include behaves the same regardless of Rails or not, so I didn't tag this question with Rails.
I even added byebug
at the end of the file of MyClass
, so that I could inspect the class and run MyClass.singleton_methods(false)
or run MyClass.instance_methods(false)
. But they still include these three unwanted methods.
I can remove these three extra methods from the array manually, so I could get the dynamic list of methods of my class, but I am just afraid that in the future my app will break if there's an update or something that will add new methods to the class (unknowingly).
UPDATE:
The 3 methods only get added in Rails 3 it seemed (the project I'm working on), but not in Rails 4 (as I and @Wand Maker has tested).
This is the exact code (where I removed already everything, but still getting same results/problem)
# lib/my_class.rb
class MyClass
include ActionView::Helpers::UrlHelper
def welcome
puts 'Hello Jules!'
end
def farewell
puts 'Goodbye Jules!'
end
end
byebug
Or I could delete that file: my_class.rb (and copy and paste that whole code in rails console
)
But, still getting the same problem.
You can do something like below:
MyClass.instance_methods(false)
#=> [:foo, :bar]
If you want to include any class methods defined in MyClass
, you could do:
MyClass.instance_methods(false) + MyClass.singleton_methods(false)
Here is working example with all classes/modules defined
class BaseClass
def moo
end
end
module AnotherBaseClass
def boo
end
end
module MyModule
def roo
end
end
class MyClass < BaseClass
extend AnotherBaseClass
include MyModule
def self.goo
end
def foo
end
def bar
end
end
p MyClass.instance_methods(false) + MyClass.singleton_methods(false)
#=> [:foo, :bar, :goo]
p RUBY_VERSION
#=> "2.2.2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With