alias_method(p1, p2)
private
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
Bad example
Note that it would be better to avoid the alias_method line in the example and just call super.
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
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
@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


