Last active
February 6, 2019 15:33
-
-
Save nightpool/14438c6765896054ea3a3eb1c66b1826 to your computer and use it in GitHub Desktop.
Module.prepend vs. alias_method_chain: FIGHT!
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
# classic situation: | |
class B1 | |
def foo | |
'B' | |
end | |
end | |
module A1 | |
def foo | |
'A' + super | |
end | |
end | |
B1.prepend A1 | |
class B1 | |
def foo_with_c | |
'C' + foo_without_c | |
end | |
alias_method_chain :foo, :c | |
end | |
# but this doesn't work!!! | |
# [13] dev (main)> B1.new.foo | |
# SystemStackError: stack level too deep | |
# This works: | |
class B2 | |
def foo | |
'B' | |
end | |
end | |
class B2 | |
def foo_with_c | |
'C' + foo_without_c | |
end | |
alias_method_chain :foo, :c | |
end | |
module A2 | |
def foo | |
'A' + super | |
end | |
end | |
B2.prepend A2 | |
# [19] dev (main)> B2.new.foo | |
# => "ACB" | |
# but it's really scary! | |
# Module#prepend is definitely the new hotness, and much better then | |
# alias_method_chain, but you need to be careful about using it in a | |
# legacy codebase, or else you can run into all sorts of issues. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment