Plugins are great in Rails, but sometimes they seem a bit much for certain tasks, such as writing a quick utility mixin. In a previous post on writing DRY validators, I discussed putting the validation mixin code inside Rails’
Although this worked, it didn’t feel clean: Rails apps come with a default
lib folder that seems much better suited to the task.
lib/application.rb acts as a start point for loading in any of your other library code. In the following example, I’ve mixed some methods into the
String class and written a small extension to
def wrap ["%", self, "%"].join end
def self.included(base) base.extend ClassMethods end module ClassMethods def acts_as_auditable include InstanceMethods end end module InstanceMethods def auditable_name self.name end end
ActiveRecord::Base.send :include ActiveRecord::Auditing```
This is a lot neater than putting everything in the
initializers folder, and allows you to correctly namespace your files. It also prevents your model, controller and view folders from becoming cluttered with utility code.