Update: Read the follow-up post Second thoughts on initializing modules
I was recently presented the problem of appending to the initialize method from a module that was being included. To do this it would need to override the class's initialize method with my own but keep the functionality of the original initialize method.
Whenever I need to do something in Ruby that I know will require some experimentation I like to move outside of my application and reproduce the problem in a simple way. For this problem I created a Person class that mixes in a Teacher module.
module Teacher
def initialize
puts "initializing teacher"
end
end
class Person
include Teacher
def initialize
puts "initializing person"
end
end
The goal is to get the following output when a Person object is created:
> Person.new
initializing teacher
initializing person
The basic program fails as expected; Teacher.new prints "initializing person" because Person's initialize is trumping Teacher's. Our immediate goal is to replace Person's initialize with Teacher's but in a way that preserves the original initialize method. By using alias_method we can create a copy of the original initialize method that we can call later.
module Teacher
def self.included(base)
base.class_eval do
alias_method :original_initialize, :initialize
def initialize
puts "initializing teacher"
original_initialize
end
end
end
end
This solution is the simplest thing that could possibly work, unfortunately it also has one major limitation. For it to work the call to include Teacher in Person has to come after Person's definition of initialize. This is may be fine in situations where you have total control over the Person class, but what if Teacher is going to be part of a library you are distributing? Asking your users to place the include line to your module in a specific spot is unacceptable.
To make this work we need to be able to capture definitions of the method we want to redefine even after our module has been included. This sounds like a good time to use Ruby's method_added hook.
module Teacher
def self.included(base)
base.extend ClassMethods
base.overwrite_initialize
base.instance_eval do
def method_added(name)
return if name != :initialize
overwrite_initialize
end
end
end
module ClassMethods
def overwrite_initialize
class_eval do
unless method_defined?(:custom_initialize)
define_method(:custom_initialize) do
puts "teacher initialized"
original_initialize
end
end
if instance_method(:initialize) != instance_method(:custom_initialize)
alias_method :original_initialize, :initialize
alias_method :initialize, :custom_initialize
end
end
end
end
end
Whoa! As you can see a lot of complexity has been added to Teacher. However, what it's doing is actually really cool. Here is the breakdown:
What self.included is doing:
- The ClassMethods module containing
overwrite_initializeis added to base (Person). - overwrite_initialize is invoked.
- method_added is defined on Person at the class level.
What overwrite_initialize does:
- If a method called
custom_initializedoes not exist it defines one.custom_initializeruns Teacher's initialize logic and then defers to Person's initialize. - If the current
initializemethod is not ourcustom_initializemethod theninitializeis preserved asoriginal_initializeand a copy ofcustom_initializeis made to replaceinitialize.
What method_added is doing:
- Watches for new methods with the name "initialize".
- When an initialize method is defined method_added calls
overwrite_initializeto put the chain from custom_initialize to this new initialize method in place.
What is particularly nice is that this implementation is flexible enough to handle multiple redefinitions of initialize. This is important because a subclass of Person may also define initialize. It is not perfect though—if the initialize in the subclass of Person calls super the program will go into an infinite loop where custom_initialize and the subclass's initialize call each other indefinitely. If anyone has a suggestion on how to get around this please post a comment or fork the gist on Github.
Read the follow-up to this post Second thoughts on initializing modules.








I think the the simplest thing that could possibly work is to have Teacher define a method called #initialize and make Person#initialize call super as the first thing. Or, more generally, have Teacher define #initialize_teacher and have Person#initialize call it at the right spot.
Your particular solution here has a number of practical problems:
1) You force the composing class to have a #initialize. This isn't too bad since you get a no-op one from Object, but it's by no means guaranteed. It also means your technique doesn't generalize to methods other than #initialize without writing guard code for when the the method doesn't exist.
2) You force the composing class to not use #method_added, since you'll blow it away when Teacher is included. This could be fixed by chaining #method_added if it's already there, but there's a slippery slope argument that can be made if you assume the presence of other modules using the #method_added trick.
3) You force the composing class's #initialize to be called after Teacher's #initialize. This can't easily be fixed with your technique. You could opt to have the composing class's #initialize be called first but that's just as bad.
I think in general your technique is bad for a fundamental reason:
It has the subordinate unit take ownership of resolving method conflicts in the composing unit. The composing unit is the only place where you have enough information to resolve the conflict accurately. You've broken a form of encapsulation by having a subordinate unit reach into the composing unit, mess with its insides, and decide the composing unit's behavior.
If you haven't already, I would suggest reading the paper on Traits. Traits, on their surface, seem similar to Ruby modules but have much stronger guarantees. One of which is that it's the responsibility of the composed class to disambiguate conflicts, which makes a lot of sense when you think about where the responsibility should belong. That paper has guided a lot of my thinking about how to write good Ruby modules.
remove
This is some pretty sweet meta-programming. It goes a bit against the current ( Rails-3-based ) trend of using super in preference to alias_method chains. Doesn't mean it's bad, just that the fragrance is out-of-fashion.
Perhaps this doesn't apply in your use case, but I'd look for a way to lazy-initialize the module when the module's behavior is being called upon, rather than trying to override the initializer of the host class.
Something like:
remove
This reminds me of a similar situation we were in recently at my company, where someone had overloaded an association method of the User model, in order to return some chosen value if a condition was met, but to otherwise default to the association. Only the implementer had erroneously used read_attribute, which only works on actual column values, not on associations.
Here's a fake example:
def region # User has a region_id but we're overloading region() return some_return_value if some_condition read_attribute(:region) # that existed before we defined this method end
Various co-workers offered 3 different approaches.
1) Use alias method chaining, thus obviously adding something like an original_region() method.
2) Just call Region.find(region_id) - which seems bad/dangerous, without having a specific example of a problem which this could cause.
3) Do this original_region = instance_method(:region) define_method :region do # now we're in the scope of the class return some_return_value if some_condition original_region.bind(self).call end
This may seem a little convoluted, and even not-so-readable. But, technically, it seems like the best approach, at least out of these three options.
remove