The deeper I dig into Rails, the more I need to know about Ruby. I have been learning more about how Ruby does OO. I came to Ruby from Java and at first things like modules were confusing for me. Recently I discovered the power of mixin modules. I was trying to figure out how to put my models into a plugin and then override or add additional functionality to those models. My main reason for doing this was to change the database referenced in the “use_db” plugin. I had a hard time finding an elegant way to do it, but mixin modules really helped me do it in simple way.
So what do mixin modules do? Basically they allow you to code instance methods into a module and then include the module in a class. The class will then have access to the instance methods in a module. Pretty nice when you have shared functionality between models. You can code one module and include it in several models.
Here is an example:
module LoudModule
def explode
"BOOM!"
end
end
class BottleRocket
include LoudModule
end
class FireCracker
include LoudModule
end
firecracker = FireCracker.new
p firecracker.explode
bottlerocket = BottleRocket.new
p bottlerocket.explode
As you can see firecracker and bottlerocket both have access to the “explode” instance method in the module.
Now to make this work with a Rails plugin where you need a model base class:
module BaseWidget
self.included?(base)
base.belongs_to :manufacturer
end
def some_instance_method
"test"
end
end
class Widget < ActiveRecord::Base
unloadable
use_db :prefix => "mydatabse_prefix_"
include BaseWidget
def some_new_instance_method
"test2"
end
end
This is pretty cool because it will allow you to define a base class for your model that you can reuse in different applications. The self.included? block allows you to load use the instance methods from the base class (ActiveRecord::Base in this case). So Widget will have access to all the associations, named_scopes and act_as* methods from the Base class.