Created
January 19, 2017 20:18
-
-
Save codeforkjeff/b1934f3aea5d34a2b169dad700f10199 to your computer and use it in GitHub Desktop.
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
# illustrates interesting effects of #extend | |
module Mixin | |
def testo | |
"in mixin" | |
end | |
end | |
class SimpleClass | |
def testo | |
"in X" | |
end | |
end | |
class ClassIncludingMixin | |
include Mixin | |
def testo | |
"in Y" | |
end | |
end | |
# no surprises | |
x = SimpleClass.new | |
fail unless x.testo == 'in X' | |
# dynamically mixin module to object. note that #testo resolves to the | |
# method in Mixin, which is NOT what happens when you #include! | |
x.extend(Mixin) | |
fail unless x.testo == 'in mixin' | |
# proof that #extend didn't change SimpleClass, only the object instance above | |
x = SimpleClass.new | |
fail unless x.testo == 'in X' | |
# mixin is already included in this class, so the method in the class | |
# takes precedence over mixin. | |
x = ClassIncludingMixin.new | |
fail unless x.testo == 'in Y' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment