Add 'big_brother_watch' method and first logging methods

master
Guillaume DOTT 2013-05-28 10:38:20 +02:00
parent 54f354b264
commit 4ebb0c52f1
3 changed files with 124 additions and 1 deletions

View File

@ -1,5 +1,48 @@
require "rails_big_brother/version" require "rails_big_brother/version"
require "rails_big_brother/controller"
require "rails_big_brother/model"
module RailsBigBrother module RailsBigBrother
# Your code goes here... def user=(value)
store[:user] = value
end
def user
store[:user]
end
def controller_info=(value)
store[:controller_info] = value
end
def controller_info
store[:controller_info]
end
def controller_info_string
case controller_info
when Array
controller_info.join(',')
when Hash
controller_info.map { |k,v| "#{k}:#{v}" }.join(',')
else
controller_info
end
end
private
def store
Thread.current[:big_brother_log] ||= {}
end
extend self
end
ActiveSupport.on_load(:active_record) do
include RailsBigBrother::Model
end
ActiveSupport.on_load(:action_controller) do
include RailsBigBrother::Controller
end end

View File

@ -0,0 +1,27 @@
module RailsBigBrother
module Controller
def self.included(base)
base.before_filter :set_log_current_user, :set_log_infos
end
protected
def big_brother_user
nil
end
def big_brother_infos
{}
end
private
def set_log_current_user
::RailsBigBrother.user = big_brother_user
end
def set_log_infos
::RailsBigBrother.controller_info = big_brother_infos
end
end
end

View File

@ -0,0 +1,53 @@
module RailsBigBrother
module Model
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def big_brother_watch(options = {})
send :include, InstanceMethods
class_attribute :big_brother_options
self.big_brother_options = {}
[:ignore, :only].each do |k|
self.big_brother_options[k] = [options[k]].flatten.compact.map(&:to_s) if options.has_key?(k)
end
after_create :log_create if !options[:on] || options[:on].include?(:create)
before_update :log_update if !options[:on] || options[:on].include?(:update)
after_destroy :log_destroy if !options[:on] || options[:on].include?(:destroy)
end
end
module InstanceMethods
private
def log_create
big_brother_log 'create'
end
def log_update
changed_fields = self.changed
changed_fields = changed_fields - self.class.big_brother_options[:ignore] if self.class.big_brother_options.has_key?(:ignore)
changed_fields = changed_fields & self.class.big_brother_options[:only] if self.class.big_brother_options.has_key?(:only)
unless changed_fields.empty?
big_brother_log 'update', changed_fields.join(',')
end
end
def log_destroy
big_brother_log 'destroy', to_s
end
def big_brother_log(action, *args)
# TODO RailsBigBrother.format, RailsBigBrother.separator
Rails.logger.info "big_brother;#{RailsBigBrother.user};" <<
"#{RailsBigBrother.controller_info_string};" <<
"#{self.class.name};#{self.to_param};#{action};#{args.join(';')}"
end
end
end
end