Created
October 31, 2008 15:08
-
-
Save Narnach/21324 to your computer and use it in GitHub Desktop.
Use a Module to overwrite a method
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 | |
# Goal: | |
# I want to overwrite an existing method on a class by using a module, | |
# instead of opening up the class and overwriting the method. | |
# | |
# Problem: | |
# Modules are treated kinda like a superclass. | |
# This means you can't use it to override a method, | |
# because it lies further away in the method call chain. | |
# | |
# My solution: | |
# When including the Module, first remove the pre-defined method from the class. | |
# External library class, think ActiveResource::Base... | |
class One | |
def name | |
'one' | |
end | |
end | |
# Define a custom name method to be used with One | |
module Name | |
def self.included(base) | |
return unless base.instance_methods(false).include?('name') | |
base.instance_eval do | |
remove_method :name | |
end | |
end | |
def name | |
self.class.name | |
end | |
end | |
# Use module to override method with own version | |
class One | |
include Name | |
end | |
# Subclass as with ActiveResource | |
class Two < One | |
end | |
puts One.new.name | |
puts Two.new.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment