2013-05-28 10:38:20 +02:00
|
|
|
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 = {}
|
|
|
|
|
2013-05-29 11:13:14 +02:00
|
|
|
[:ignore, :only, :verbose].each do |k|
|
2013-05-28 10:38:20 +02:00
|
|
|
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?
|
2013-05-29 15:33:52 +02:00
|
|
|
fields_hash = changed_fields.inject({}) do |hash, field|
|
|
|
|
hash[field] = (
|
2013-05-29 11:46:31 +02:00
|
|
|
self.class.big_brother_options.has_key?(:verbose) &&
|
2013-05-29 15:33:52 +02:00
|
|
|
self.class.big_brother_options[:verbose].include?(field) ? send(field).to_s : ''
|
|
|
|
)
|
|
|
|
|
|
|
|
hash
|
|
|
|
end
|
|
|
|
big_brother_log 'update', RailsBigBrother.hash_to_s.call(fields_hash)
|
2013-05-28 10:38:20 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def log_destroy
|
|
|
|
big_brother_log 'destroy', to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
def big_brother_log(action, *args)
|
2013-05-29 14:31:50 +02:00
|
|
|
RailsBigBrother.logger.info RailsBigBrother.format %
|
2013-05-28 12:01:15 +02:00
|
|
|
{
|
|
|
|
user: RailsBigBrother.user,
|
|
|
|
controller_info: RailsBigBrother.controller_info_string,
|
|
|
|
class: self.class.name,
|
|
|
|
id: self.to_param,
|
|
|
|
action: action,
|
2013-05-29 15:33:52 +02:00
|
|
|
args: RailsBigBrother.array_to_s.call(args)
|
2013-05-28 12:01:15 +02:00
|
|
|
}
|
2013-05-28 10:38:20 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|