Created
November 10, 2011 09:23
-
-
Save wycats/1354486 to your computer and use it in GitHub Desktop.
Shows how Ruby mixins work together with `super`
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
| ## | |
| ## with raw object | |
| ## | |
| # create a new object | |
| o = Object.new | |
| # define methods on the object (precisely, the object's singleton) | |
| class << o | |
| def hello(thing) | |
| puts "hello #{thing}" | |
| end | |
| end | |
| module Yeller | |
| def hello(thing) | |
| super thing.upcase | |
| end | |
| end | |
| module Queryer | |
| def hello(thing) | |
| super "#{thing}?" | |
| end | |
| end | |
| # apply the Yeller mixin to the object | |
| o.extend Yeller | |
| # apply the Queryer mixin to the object | |
| o.extend Queryer | |
| o.hello "world" #=> hello WORLD? | |
| ## | |
| ## with classes | |
| ## | |
| class Person | |
| include Yeller | |
| include Queryer | |
| def hello(thing) | |
| puts "hello #{thing}" | |
| end | |
| end | |
| Person.new.hello "world" #=> hello WORLD? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is printing "hello world" for me for both
o.helloandPerson.new.hello. The only way this works for me is if I subclass Person and include the modules on the subclass: