You can easily get source code for a method in Ruby.
Imagine the following hypothetical class:
class Klass
def self.foo
:foo
end
def bar
:bar
end
end
As you can see, this class has two methods:
- a class method .foo
- an instance method #bar
Use .method
and .instance_method
to access them programmatically:
m1 = Klass.method :foo
=> #<Method: Klass.foo>
m2 = Klass.instance_method :bar
=> #<UnboundMethod: Klass#bar>
You can use the .source
method to view their source code:
puts m1.source
def self.foo
:foo
end
=> nil
puts m2.source
def self.bar
:bar
end
=> nil
Because Ruby has open classes and dynamic loading, you can also add or
change methods at run time. Just re-open the class and redefine the method:
Klass.foo
=> :foo
class Klass
def self.foo
:foobar
end
end
Klass.foo
=> :footer
The other methods previously defined in the class will remain unaffected:
Klass.bar
=> :bar
WARNING: Redefining class behavior during runtime (also called "Monkey Patching")
is a very powerful tool, it can also be somewhat dangerous. Current versions of Ruby
support a much more controlled way of going about this called 'refinements'.
You can learn more about using refinements here