Skip to content

Instantly share code, notes, and snippets.

@skarayan
Created August 2, 2012 18:06
Show Gist options
  • Save skarayan/3239208 to your computer and use it in GitHub Desktop.
Save skarayan/3239208 to your computer and use it in GitHub Desktop.
Set current_user on all models in before_* callback
# lib/user_stamp.rb
module UserStamp
def self.included(klass)
callbacks = [:before_validation, :before_save, :before_create, :before_update]
callbacks.each do |callback|
klass.send(callback) do
return unless respond_to?(:updated_by) || updated_by.nil?
self.updated_by = Thread.current[:current_user]
end
end
end
end
# config/initializers/add_user_stamp.rb
require 'user_stamp'
Dir[Rails.root + "app/models/**/*.rb"].each do |path|
require path
klass = path.gsub(/^.+\//,'').gsub(/\.rb/,'').camelize.constantize
klass.class_eval { include UserStamp }
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_current_user
private
def current_user
# ...
end
def set_current_user
Thread.current[:current_user] = current_user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment