Rails: Writing library code

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' config/initializers directory.

Although this worked, it didn't feel clean: Rails apps come with a default lib folder that seems much better suited to the task.

Since reading this post on Rails' other files. I've used the following setup in projects such as Amberleaf to load all the mixins and utility code that doesn't warrant its own plugin:

# config/initializers/application.rb
require 'lib/application.rb'

The 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 ActiveRecord::Base.

# lib/application.rb
require 'core_ext/string.rb'
require 'core_ext/array.rb'

require 'active_record/auditing.rb'

# lib/core_ext/string.rb
module CoreExt
  String.class_eval do
    def wrap
      ["%", self, "%"].join
    end
  end
end

# lib/active_record/auditing.rb
module ActiveRecord
  module Auditing
    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
  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.

« Previous Post

avatar

Chris Blunt

Plymouth Software

Devon, England

twitter.com/cblunt

github.com/cblunt

 

facebook.com/cbluntuk

flickr.com/photos/cblunt