public
Last active

  • Download Gist
Overview.rdoc
RDoc

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.

the-problem.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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"
the-solution.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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!

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.