Quick what's new here hack

Sometimes you may need to flag a model as being new or recently updated, within in certain time constraint.

Monkey patch/plugin

module Marmalade
  module ActiveRecord
    module Acts
      module Recent

        def self.included( klass )
          super
          klass.extend(ClassMethods)
        end     

        module ClassMethods

          def acts_as_recent( threshold = 5.days )
            class_inheritable_accessor :recent_threshold
            self.recent_threshold = threshold.is_a?( Fixnum ) ? threshold : 5.days
            send :include, Marmalade::ActiveRecord::Acts::Recent::InstanceMethods 
          end
        end

        module InstanceMethods

          def fresh?
            created_at && created_at > Time.now.utc.ago(recent_threshold)
          end

          def recently_updated?
            updated_at && updated_at > Time.now.utc.ago(recent_threshold)  
          end        

        end

      end
    end
  end
end

ActiveRecord::Base.class_eval { include Marmalade::ActiveRecord::Acts::Recent }

Usage

A Fixnum argument is expected.That's on purpose.The ActiveSupport Time extensions makes for clean DSL like reading.

class Booking < ActiveRecord::Base
  acts_as_recent 5.days #3.hours, 1.week etc.

end

Examples

>> b.created_at
=> Mon Nov 20 10:21:23 UTC 2006
>> b.fresh?
=> true
>> b.recently_updated?
=> true
>> b.created_at = Time.now.utc.ago(10.days)
=> Fri Nov 10 19:44:59 UTC 2006
>> b.fresh?
=> false
>> new_bookings, old_bookings = Account.find(2).bookings.by_status(:awaiting_payment).partition{|b| b.fresh?}

About this entry