Skip to content

Instantly share code, notes, and snippets.

@gawin
Created Sep 16, 2010
Embed
What would you like to do?
# encoding: utf-8
module Mongoid #:nodoc:
# Include this module to set the creator of documents.
# This will add a created_at and updated_at field to the +Document+, managed automatically.
#
# To use:
#
# class Person
# include Mongoid::Document
# include Mongoid::Userstamps
# end
module Userstamps
module Stampable
extend ActiveSupport::Concern
included do
field :created_by, :type => String
field :updated_by, :type => String
set_callback :create, :before, :set_created_by
set_callback :save, :before, :set_updated_by
class_inheritable_accessor :record_userstamps, :instance_writer => false
self.record_userstamps = true
end
# Update the created_by field on the Document to the current user.
# This is only called on create.
def set_created_by
if !created_by
self.created_by = self.stamper
end
end
# Update the updated_by field on the Document to the current user.
# This is only called on create and on save.
def set_updated_by
self.updated_by = self.stamper
end
end
module Stamper
# in je application include Mongoid::Userstamps::Stamper
def self.included(base) # :nodoc:
puts base.class
base.send :include, InstanceMethods
base.before_save :set_stamper
base.before_update :set_stamper
base.after_save :reset_stamper
base.after_update :reset_stamper
end
module InstanceMethods
private
def set_stamper
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"] = current_user
end
def stamper
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"]
end
def reset_stamper
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"] = nil
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment