Print all method names of a class in Ruby?
Try this one-liner:
puts 5.methods.sort
Ruby module to print all method calls and returns in class
You can achieve that by defining a new wrapper method for each public instance method of the class that performs the log logic that you need.
module Loginator
def logify_me
self.public_instance_methods.each do |method|
proxy = Module.new do
define_method(method) do |*args|
puts "Method #{method}(#{args.join(', ')}) called"
# added join to match the exact desired output
value = super *args
puts "returns #{value}"
value
end
end
self.prepend proxy
end
end
end
class A
extend Loginator
def add(a, b)
a + b
end
def sub(a, b)
a - b
end
logify_me
end
Which yields the following output:
>> A.new.sub(1,2)
Method 'sub' called with args '[1, 2]'
returns -1
=> -1
>> A.new.add(4,7)
Method 'add' called with args '[4, 7]'
returns 11
=> 11
Explanation for the future :)
define_method(method)
:Defines an instance method in the receiver. The method parameter can be a Proc, a Method, or an UnboundMethod object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval ref. can be found here
prepend
prepend will insert the module at the bottom of the chain, even before the class itself.fourth ref on my post
Section to Edit by @pedrosfdcarneiro
please, add some brief explanation about the second inner module proxy = Module.new do end
and why it's important for the return value and the usage of the super.
plus why did you preferred to use the public_instance_methods
over instance_methods
.
please kindly add some explanation about it because first its a bit unclear to me and secondly for the other noobs out there.
thanks in advance :)
This answer was heavily based on this fantastic answer: https://stackoverflow.com/a/23898539/1781212.
Get list of a class' instance methods
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass
def method1
end
def method2
end
def method3
end
end
TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]
How to list all methods for an object in Ruby?
The following will list the methods that the User class has that the base Object class does not have...
>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
"content_columns", "su_pw?", "default_timezone", "encode_quoted_value",
"reloadable?", "update", "reset_sequence_name", "default_timezone=",
"validate_find_options", "find_on_conditions_without_deprecation",
"validates_size_of", "execute_simple_calculation", "attr_protected",
"reflections", "table_name_prefix", ...
Note that methods
is a method for Classes and for Class instances.
Here's the methods that my User class has that are not in the ActiveRecord base class:
>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user",
"original_table_name", "field_type", "authenticate", "set_default_order",
"id_name?", "id_name_column", "original_locking_column", "default_order",
"subclass_associations", ...
# I ran the statements in the console.
Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods
call.
Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing
and responds_to
techniques to handle method calls on the fly. As a result, the methods are not listed in the methods
method result.
Print all methods defined in a ruby file
When free functions are defined in Ruby, they become private methods on the Object class. there is a default instance of the Object class which is the self context for ruby code outside of a class block, called the main instance.
initial_methods = private_methods
def func_a
end
def func_b
end
final_methods = private_methods
new_methods = final_methods - initial_methods
puts "#{new_methods.join}"
Ruby print out only the class methods (and not inherited methods)
methods(regular=true) → array
Returns a list of the names of public
and protected methods of obj. This will include all the methods
accessible in obj's ancestors. If the optional parameter is false, it
returns an array of obj's public and protected singleton methods, the
array will not include methods in modules included in obj.
- https://ruby-doc.org/core-2.7.1/Object.html#method-i-methods
Module#instance_methods
has the exact same signature.
module Bannable
def ban!
@banned = true
end
end
class Parent
include Bannable
def a_parent_instance_method
end
def self.a_parent_class_method
end
end
class Child < Parent
def a_child_instance_method
end
def self.a_child_class_method
end
end
irb(main):024:0> Child.methods(false)
=> [:a_child_class_method]
irb(main):025:0> Child.instance_methods(false)
=> [:a_child_instance_method]
How to list all methods of a class (not Extended and Included methods)
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"
How to list all the methods defined in top self Object in Ruby?
The closest I could find is to call private_methods
on the main
object, with false
as argument
Returns the list of private methods accessible to obj. If the all
parameter is set to false, only those methods in the receiver will be
listed.
def foo
"foo"
end
def bar
"bar"
end
def baz
"baz"
end
p private_methods(false)
# [:include, :using, :public, :private, :define_method, :DelegateClass, :foo, :bar, :baz]
If you omit the argument, you also get all the private methods defined in Kernel
or BasicObject
.
In order to refine the list further, you could select the methods defined for Object
:
p private_methods(false).select{|m| method(m).owner == Object}
#=> [:DelegateClass, :foo, :bar, :baz]
Only :DelegateClass
is left, because it is defined in the top-level scope, just like :foo
, :bar
and :baz
.
How to get a detailed list of methods defined in a Ruby class via the command line?
Use instance_methods
for that class and then query the parameters
e.g.
class A
def foo
end
def bar(a,b,c)
end
end
A.instance_methods(false).each do |s|
print "def #{s}(#{A.instance_method(s).parameters})\n"
end
Output:
def foo([])
def bar([[:req, :a], [:req, :b], [:req, :c]])
You might need to get subprocess the parameters array to get the name only.
As for command line, just save it into a ruby script.
Related Topics
How to Turn a Ruby Method into a Block
Use Global or Constant Variable in Ruby/Rails
Subtract Dates in Ruby and Get the Difference in Minutes
How to Use Ruby Metaprogramming to Add Callbacks to a Rails Model
How to Get a HTML Table Row with Capybara
Testing a Concern/Module That Uses Activerecord
Multiple Blogs in Single Jekyll Website
How to Configure Mongomapper and Activerecord in Same Ruby Rails Project
What's the Fastest Way to Check If a Word from One String Is in Another String
How to Establish a Ssl Enabled Tcp/Ip Connection in Ruby
How to Use Nokogiri::Xml::Reader to Parse Large Xml Files
Parallel Http Requests in Ruby