Created
October 1, 2012 00:04
-
-
Save prodis/3808790 to your computer and use it in GitHub Desktop.
Ruby Fundamental - Alias para métodos em Ruby
This file contains hidden or 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
names = ["Akira", "Fernando", "Jose"] | |
names.length # => 3 | |
names.size # => 3 |
This file contains hidden or 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 MyClass1 | |
def do_something | |
"Doing..." | |
end | |
alias_method :make_something, :do_something | |
end | |
m1 = MyClass1.new | |
m1.do_something # => "Doing..." | |
m1.make_something # => "Doing..." |
This file contains hidden or 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 MyClass2 | |
def do_something | |
"Doing..." | |
end | |
alias_method :do_something_original, :do_something | |
def do_something | |
"#{do_something_original} And doing more here..." | |
end | |
end | |
m2 = MyClass2.new | |
m2.do_something # => "Doing... And doing more here..." |
This file contains hidden or 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
# You didn't write this code | |
class ExternalClass | |
def some_number | |
456 # Just to exemplify | |
end | |
end | |
# You wrote this code | |
class ExternalClass | |
alias_method :some_number_original, :some_number | |
def some_number | |
some_number_original + 100 | |
end | |
end | |
external = ExternalClass.new | |
external.some_number # => 556 |
This file contains hidden or 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
# You didn't write this code | |
class ExternalClass | |
def some_number | |
456 # Just to exemplify | |
end | |
end | |
# You wrote this code | |
module SomeModule | |
def self.included(base) | |
base.class_eval do | |
alias_method :some_number_original, :some_number | |
def some_number | |
some_number_original + 100 | |
end | |
end | |
end | |
end | |
e1 = ExternalClass.new | |
e1.some_number # => 456 | |
ExternalClass.send(:include, SomeModule) | |
e2 = ExternalClass.new | |
e2.some_number # => 556 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment