Winter Logger

Posted on December 8th, 2008

It's a trifling, but tis the season - here's a simple way to add Rails logging functionality to a model that does not extend ActiveRecord::Base.

# logging.rb, place in lib directory
# Include to enable Rails logging in a class that does not extend a Rails base class.
module Logging
  def self.included(base)
    base.class_eval do
      extend Methods  # Add logger() class method
      include Methods # Add logger() instance method
    end
  end

  module Methods
    def logger
      RAILS_DEFAULT_LOGGER
    end
  end
end

# Non-ActiveRecord model to which to add logger methods
class PlainOldRubyModel
  include Logging
end

# In environment.rb or an initalizer
require 'logging'

    2 Responses

  • John

    Thanks for the info! I was banging my head against the wall trying to figure out an elegant way of including the logger in my non AR class. Looks like this will do the trick.

  • Shayne Desormo

    Extremely well composed composition, if only all bloggers produced the equivalent content as you, the internet would be a much better place.

Leave a Reply

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.