Skip to content

Instantly share code, notes, and snippets.

@nicklewis
Created January 31, 2011 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklewis/804871 to your computer and use it in GitHub Desktop.
Save nicklewis/804871 to your computer and use it in GitHub Desktop.
An example of aliasing in a singleton class copying a method definition
class MyClass
def my_instance_method
:some_value
end
end
instance = MyClass.new
singleton_class = class << instance; self; end
puts singleton_class.instance_method(:my_instance_method) == MyClass.instance_method(:my_instance_method)
class << instance
alias_method :temporary_method, :my_instance_method
alias_method :my_instance_method, :temporary_method
end
class MyClass
def my_instance_method
:some_other_value
end
end
# Singleton class now has the original version of the method
puts singleton_class.instance_method(:my_instance_method) == MyClass.instance_method(:my_instance_method)
singleton_class.instance_method(:my_instance_method).bind(instance).call # :some_value
MyClass.instance_method(:my_instance_method).bind(instance).call # :some_other_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment