Skip to content

Instantly share code, notes, and snippets.

@wycats
Created November 10, 2011 09:23
Show Gist options
  • Save wycats/1354486 to your computer and use it in GitHub Desktop.
Save wycats/1354486 to your computer and use it in GitHub Desktop.
Shows how Ruby mixins work together with `super`
##
## 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?
@phuibonhoa
Copy link

This is printing "hello world" for me for both o.hello and Person.new.hello. The only way this works for me is if I subclass Person and include the modules on the subclass:

class Person

  def hello(thing)
    puts "hello #{thing}"
  end
end

class Owner < Person
  include Yeller
  include Queryer

end

Person.new.hello "world" #=> hello world
Owner.new.hello "world" #=> hello WORLD?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment