Created
December 9, 2013 13:26
-
-
Save pataiji/7872200 to your computer and use it in GitHub Desktop.
https://github.com/pokonski/public_activity の拡張。modelでインクルードして使うととりあえずトラックしまくる。消すのは忍びないので置いておく。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 使用したいモデルでインクルード | |
# ex) include Concerns::ActivityTracker | |
module Concerns::PublicActivityTracker | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# create, update, destroy を監視します。 | |
# 引数に only か except を渡すことで update を監視したいカラムを限定できます。 | |
# | |
# ex) track_enable | |
# ex) track_enable only: [:name, :updated_at] | |
# ex) track_enable except: [:name, :updated_at] | |
def track_enable(options = Hash.new) | |
if options.present? | |
if !options.instance_of?(Hash) | |
raise 'Invalid options' | |
elsif options.keys.reject{|k| [:only, :except].include? k}.present? | |
raise 'Invalid options' | |
else | |
[:only, :except].each do |key| | |
option = options[key].presence | |
if option.present? | |
if option.instance_of?(String) || option.instance_of?(Symbol) | |
options[key] = [option.to_s] | |
elsif !option.instance_of?(Hash) | |
raise 'Invalid options' | |
end | |
end | |
end | |
end | |
end | |
attrs = self.attribute_names - ['id'] | |
if options[:only].present? | |
attrs &= options[:only] | |
elsif options[:except].present? | |
attrs -= options[:except] | |
end | |
define_method :tracking_activity_on_update do | |
attrs.each do |a| | |
if self.instance_eval("#{a}_changed?") | |
self.create_activity :update, get_controller_options | |
break | |
end | |
end | |
end | |
private :tracking_activity_on_update | |
self.send('after_create', :'tracking_activity_on_create') | |
self.send('after_update', :'tracking_activity_on_update') | |
self.send('before_destroy', :'tracking_activity_on_destroy') | |
end | |
end | |
private | |
def tracking_activity_on_create | |
self.create_activity :create, get_controller_options | |
end | |
def tracking_activity_on_destroy | |
self.create_activity :destroy, get_controller_options | |
end | |
def get_controller_options | |
controller = PublicActivity.get_controller | |
controller.present? ? { owner: controller.current_user, params: controller.params } : nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment