Daniel A. R. Werner Daniel A. R. Werner - 4 months ago 14
Ruby Question

Calling original method from a redefined one

My question is based on an answer to the topic “redefining a single ruby method on a single instance with a lambda”.

How can I redefine a method and from within the new method call the original definition? Other instances of

some_object
's class should not become affected.

def some_object.some_method
# call original `some_object.some_method` here
do_something_else
end

Answer

If some_object.some_method is not a singleton method, then you can just call super in your redefined method.

def some_object.some_method
  super
  do_something_else
end

If some_object.some_method is a singleton method, then

Ruby >= 2.0.0

You can define that method in a module

module SomeModule
  def some_method
    super
    do_something_else
  end
end

And then prepend it to the singleton class of the object

some_object.singleton_class.prepend(SomeModule)

Ruby < 2.0.0

You have to make an alias then redefine, since there is no Module#prepend.

class << some_object  # open the singleton class of some_object
  alias some_method_original some_method

  def some_method
    some_method_original
    do_something_else
  end
end
Comments