In my last article I talked about adding a deleted_at field to the migration timestamps method for use with acts_as_paranoid.  One of the additional things I wanted to do was not only capture the timestamp information, but also the user information. This way, I can be really paranoid and see who did what when.  To add userstamps, I did the following.
lib/userstamps.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
module ActiveRecord
  module Userstamp
    def self.included(base) #:nodoc:
      base.class_eval do
        alias_method_chain :create, :userstamps
        alias_method_chain :update, :userstamps
        def current_user
          Thread.current['user']
        end
      end
    end
  private
    def create_with_userstamps #:nodoc:
      user = current_user
      if not user.nil?
        write_attribute('created_by', user.id) if respond_to?(:created_by) and created_by.nil?
        write_attribute('updated_by', user.id) if respond_to?(:updated_by) and updated_by.nil?
      end
      create_without_userstamps
    end
    def update_with_userstamps #:nodoc:
      user = current_user
      write_attribute('updated_by', user.id) if respond_to?(:updated_by) and (not user.nil?)
      update_without_userstamps
    end
  end
end
config/environment.rb (add)
1
2
3
4
require 'userstamp'
ActiveRecord::Base.class_eval do
  include ActiveRecord::Userstamp
end
    
  
Need web application development, maintenance for your existing app, or a third party code review?
Velocity Labs can help.
Hire us!