Skip to content

Instantly share code, notes, and snippets.

@nightpool
Last active February 6, 2019 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightpool/14438c6765896054ea3a3eb1c66b1826 to your computer and use it in GitHub Desktop.
Save nightpool/14438c6765896054ea3a3eb1c66b1826 to your computer and use it in GitHub Desktop.
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