Skip to content

Instantly share code, notes, and snippets.

@codeforkjeff
Created January 19, 2017 20:18
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 codeforkjeff/b1934f3aea5d34a2b169dad700f10199 to your computer and use it in GitHub Desktop.
Save codeforkjeff/b1934f3aea5d34a2b169dad700f10199 to your computer and use it in GitHub Desktop.
# 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