Created
January 31, 2011 21:38
-
-
Save nicklewis/804871 to your computer and use it in GitHub Desktop.
An example of aliasing in a singleton class copying a method definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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