Skip to content

Instantly share code, notes, and snippets.

@gawin
Created September 16, 2010 08:44
Show Gist options
  • Save gawin/582144 to your computer and use it in GitHub Desktop.
Save gawin/582144 to your computer and use it in GitHub Desktop.
# 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 = Thread.current["#{self.to_s.downcase}_#{self.object_id}_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 = Thread.current["#{self.to_s.downcase}_#{self.object_id}_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_filter :set_stamper
base.after_filter :reset_stamper
end
module InstanceMethods
private
def set_stamper
Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"] = current_user
puts "current_user = #{current_user.to_s}"
puts "stamper = #{Thread.current["#{self.to_s.downcase}_#{self.object_id}_stamper"].to_s}"
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