Created
July 30, 2010 01:35
-
-
Save scottwb/499673 to your computer and use it in GitHub Desktop.
Ruby mixin overriding instance methods.
This file contains 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
#!/usr/bin/env ruby | |
# | |
# Example showing how to make including a mixin override instance methods. | |
# | |
module TalksLikeMrT | |
def self.included(klass) | |
(klass.instance_methods & self.instance_methods).each do |method| | |
klass.instance_eval{remove_method method.to_sym} | |
end | |
end | |
def say_your_name | |
puts "My name is #{name}, fool!" | |
end | |
end | |
class Person | |
def name | |
"Mr. T" | |
end | |
def say_your_name | |
puts name | |
end | |
# Try commenting out this line. You'll get just the name. Put it back in, | |
# and you get it said like Mr. T. | |
include TalksLikeMrT | |
end | |
Person.new.say_your_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment