How To Create A Mixin To Extend Core Types in Rails 2.x
January 21, 2008 | rails
Recently I wanted to create a mixin for String in my Rails 2.0 project that allowed me to DRY up pluralization given an arbitrary number. Here’s an example usage:
"mile".pluralize_for(trip.miles) #returns "mile" when trip.miles is one and "miles" otherwise.
The mixin code is simple:
# martian_extensions.rb
module MartianExtensions
def pluralize_for(number)
unless number == 1
self.to_s.pluralize
else
self.to_s
end
end
end
The challenge came with finding a simple, configuration-free way to ensure that this mixin is loaded. Following the guidance of Jamis Buck in this (by now ancient) blog article, i eventually settled on his solution of creating my simple mixin as a full-fledged plugin.
In order to do this without adding any configuration, you can follow Rails’ automagic loading rules, namely, create an apt folder structure under your vendor/plugins directory:
/vendor/plugins/martian_extensions/
/vendor/plugins/martian_extensions/init.rb
/vendor/plugins/martian_extensions/lib
/vendor/plugins/martian_extensions/lib/martian_extensions.rb
You’ve already seen martian_extensions.rb, as for init.rb, that’s what does the work of ensuring String loads my module and includes pluralize_for:
#init.rb String.send :include, MartianExtensions
Personally, I’ll keep my core extensions in this single plugin so that I can keep it portable between my applications. It seems pretty clean to me, but if there’s a better solution that you have found, please comment!