Created
February 26, 2013 13:03
-
-
Save andywenk/5038259 to your computer and use it in GitHub Desktop.
Sample code to show alias and alias_method is working in Ruby. The related blogpost can be found here: http://goo.gl/4dhVy
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
#!/usr/bin/env ruby | |
class NoAlias | |
def nice_method | |
puts 'I am the nice method' | |
end | |
def even_nicer_method | |
puts 'I am the even nicer method' | |
end | |
end | |
class AliasMethod | |
def even_nicer_method | |
puts 'AliasMethod::even_nicer_method called' | |
end | |
alias_method :nice_method, :even_nicer_method | |
end | |
class Alias | |
def even_nicer_method | |
puts 'Alias::even_nicer_method called' | |
end | |
alias :nice_method :even_nicer_method | |
end | |
class Mother | |
def say_name | |
puts 'I am the Mother' | |
end | |
alias :name :say_name | |
end | |
class Child < Mother | |
def say_name | |
puts 'I am the Child' | |
end | |
end | |
class MotherScope | |
def say_name | |
puts 'I am the Mother' | |
end | |
def self.my_name | |
#alias :name :say_name | |
alias_method :name, :say_name | |
end | |
end | |
class ChildScope < MotherScope | |
def say_name | |
puts 'I am the Child' | |
end | |
my_name | |
end | |
puts 'Example without alias' | |
NoAlias.new.nice_method | |
NoAlias.new.even_nicer_method | |
puts | |
puts 'Example with usage of alias_method' | |
AliasMethod.new.nice_method | |
puts | |
puts 'Example with the usage of alias' | |
Alias.new.nice_method | |
puts | |
puts 'Example for inheritance' | |
Child.new.name | |
puts | |
puts 'Example for class methods in inheritance (scope!)' | |
ChildScope.new.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment