Skip to content

Instantly share code, notes, and snippets.

@nightpool nightpool/code.rb
Last active Feb 6, 2019

Embed
What would you like to do?
Module.prepend vs. alias_method_chain: FIGHT!
# 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
You can’t perform that action at this time.