Created
June 12, 2011 04:47
-
-
Save mimosz/1021264 to your computer and use it in GitHub Desktop.
Mongoid::Activity::Trackable
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
## 引入文件 | |
# require 'mongoid/activity' | |
## 插入Document行後 | |
# include Mongoid::Activity::Trackable | |
# 啟用跟蹤 | |
# tracking :person => :follower, :scope => :followable, :create_bones => 5, :destroy_bones => -3 | |
module Mongoid | |
module Activity | |
module Trackable | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :trackable_options | |
end | |
module ClassMethods | |
def tracking(options={}) | |
model_name = self.name.tableize.singularize.to_sym | |
default_options = { | |
:activity => true, | |
:person => :person, | |
:scope => nil, | |
:create => true, | |
:create_bones => nil, | |
:destroy => true, | |
:destroy_bones => nil, | |
:update => false, | |
:update_bones => nil, | |
} | |
options = default_options.merge(options) | |
before_create :track_create if options[:create] | |
before_update :track_update if options[:update] | |
before_destroy :track_destroy if options[:destroy] | |
# 賦值 | |
self.trackable_options = options | |
end | |
end | |
module InstanceMethods | |
private | |
def track_update | |
delayed_job('update', self.trackable_options[:update_bones]) | |
end | |
def track_create | |
delayed_job('create', self.trackable_options[:create_bones]) | |
end | |
def track_destroy | |
delayed_job('destroy', self.trackable_options[:destroy_bones]) | |
end | |
# 排隊 | |
def delayed_job(action, bones = nil) | |
bone = true | |
# 狗骨頭 | |
unless bones.nil? | |
bone = worker("Bone".constantize.new(:action => action, :amount => bones)) | |
end | |
# 動態 | |
if self.trackable_options[:activity] && bone | |
worker("Activity".constantize.new(:action => action)) | |
end | |
end | |
# 執行 | |
def worker(track) | |
track.trackable = self | |
track.person = send(self.trackable_options[:person]) | |
track.scope = if self.trackable_options[:scope].nil? | |
self | |
else | |
send(self.trackable_options[:scope]) | |
end | |
unless track.save | |
self.errors = track.errors | |
return false | |
end | |
return true | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment