Flowdock
alias_method(p1, p2) public

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

   module Mod
     alias_method :orig_exit, :exit
     def exit(code=0)
       puts "Exiting with code #{code}"
       orig_exit(code)
     end
   end
   include Mod
   exit(99)

produces:

   Exiting with code 99
Show source
Register or log in to add new notes.
April 8, 2010
2 thanks

Bad example

Note that it would be better to avoid the alias_method line in the example and just call super.

March 3, 2011
0 thanks

Perfectly applicable

@rkh You would be correct if this code had occurred in a subclass who’s parent method was being overridden.

However, defining the method in this manner is completely removing the old method - as if you had written code like this:

class MyClass
  def do_something
    puts "We're doing some stuff here"
  end

  def do_something
    puts "The old do_something method no longer exists!"
  end
end

MyClass.new.do_something
# => "The old do_something method no longer exists!"

Of course this is non-sensical. But the idea is that you have either included a module, or monkey-patched an already existent class, and completely replaced the old method. super(*args) will not work

October 10, 2012 - (>= v1_9_1_378)
0 thanks

Bad Example

@nZifnab it is a bad example because an included module is basically a class.

module Mod
    def exit(code = 0)
        puts "Exiting with code #{code}"
        super
    end
end

include Mod

exit 99

produces

Exiting with code 99
December 10, 2012
0 thanks

@drewyoung1

Including module in a class does not automatically over-write methods defined with the same name.

Ex:

module Mod

def exit(code = 0)
  puts "Exiting with code #{code}"
  super
end

end

class OriginalClass

include Mod
def exit
  puts "Original message"
end

end

OriginalClass.new.exit 99

Produces:

exit': wrong number of arguments (1 for 0) (ArgumentError)

if you use this construct, the alias_method will work similar to super:

module Mod

alias_method :super_exit, :exit
def self.included base
  base.instance_eval do
    def exit(code = 0)
      puts "Exiting with code #{code}"
      super_exit
    end
  end
end

end