#
# How to use alias to redefine or mock a class method.
#
# This example will show how to redefine a class method,
# then restore the method back to it's original behavior.
#
# by Greg Houston
# blog: http://ghouston.blogspot.com/
#
# Also of note, the gem Mocha uses the same technique to mock class methods.
# We will need access to the meta class.
module Kernel
# singleton_class => singleton class of receiver
#
# source: http://ola-bini.blogspot.com/2006/09/ruby-metaprogramming-techniques.html
# source: RCR231
#
unless Kernel.respond_to? :singleton_class
def singleton_class
class << self; self; end
end
end
end
# the Brain is our lab rat for this example
class Brain
def Brain.who
"I am the Brain"
end
end
# first, alias the method we will redefine...
Brain.singleton_class.class_eval do
alias :backup :who
end
Brain.who #=> I am the Brain
Brain.backup #=> I am the Brain
# second, redefine the method
Brain.singleton_class.send :define_method, :who do
"Actually I am a genetically altered lab mouse bent on world domination!"
end
Brain.who #=> Actually I am a genetically altered lab mouse bent on world domination!
Brain.backup #=> I am the Brain
# third, restore the original definition, and remove the backup...
Brain.singleton_class.class_eval do
alias :who :backup
undef :backup
end
Brain.who #=> I am the Brain
Brain.backup #=> undefined method `backup' for Brain:Class (NoMethodError)