Skip to content

@mlanza /Overview.rdoc
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Overriding a Class's Methods Using A Mixin

The Problem

You want a module to be mixed in to your class. Your class defines methods of the same names as the methods found in the module. The intent is that the module's same-named methods would override the class's methods; however, this is not the default behavior in Ruby.

Chad Fowler describes this issue:

chadfowler.com/2009/7/8/how-ruby-mixins-work-with-inheritance

It's been mentioned on Stack Overflow too:

stackoverflow.com/questions/1282864/ruby-inheritance-vs-mixins

The Solution

Some people handle this with alias_method_chain; however, there is a cleaner alternative. Simply move the class's methods into its own module and include that module in the class. This also gives you the ability to call “super” if desired.

module WizardSkills
def trick
puts "The #{self.class} turned a man into a rabbit!"
end
end
class Magician
include WizardSkills
def trick
puts "The #{self.class} pulled a rabbit out of a hat"
end
end
Magician.new.trick #=> "The Magician pulled a rabbit out of a hat"
module WizardSkills
def trick
puts "The #{self.class} turned a man into a rabbit!"
end
end
#The key is moving what used to be the class's methods to its own module
module MagicianSkills
def trick
puts "The #{self.class} pulled a rabbit out of a hat"
end
end
class Magician
include MagicianSkills
include WizardSkills
end
Magician.new.trick #=> The Magician turned a man into a rabbit!
@wiseland

Overriding a Class’s Methods Using A Mixin
May be "Overriding an Instance's Methods Using A Mixin"?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.