mileszs
11/9/2009 - 5:34 PM

user_stamp.rb

module ActiveRecord

  module UserStamp
    
    def self.included(base)
      base.class_eval do
        alias_method :create_without_user, :create
        alias_method :create, :create_with_user

        alias_method :update_without_user, :update
        alias_method :update, :update_with_user
      end
    end

    def create_with_user
      user_id = User.current_user
      self[:created_by] = user_id if respond_to?(:created_by) && created_by.nil?
      self[:updated_by] = user_id if respond_to?(:updated_by) && updated_by.nil?
      create_without_user
    end

    def update_with_user
      user_id = User.current_user
      self[:updated_by] = user_id if respond_to?(:updated_by)
      update_without_user
    end

    def created_by
      begin
        User.find(self[:created_by])
      rescue ActiveRecord::RecordNotFound
        nil
      end
    end

    def updated_by
      begin
        User.find(self[:updated_by])
      rescue ActiveRecord::RecordNotFound
        nil
      end
    end

  end

end