Created
June 14, 2011 11:01
-
-
Save kronos/1024686 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module FieldTracker | |
def self.included(cls) | |
cls.extend(ClassMethods) | |
cls.before_save :save_changes | |
cls.after_save :check_changes | |
end | |
def save_changes | |
@changes ||= [] | |
hash = {} | |
changes.each do |field,(_,value)| | |
hash[field.to_sym] = value | |
end | |
@changes.push(hash) | |
end | |
def check_changes | |
changes = @changes.pop | |
return if changes.empty? | |
self.class.tracked_fields.each do |fields, block| | |
hash = changes.select {|k,v| fields.include?(k)} | |
block.call(self, hash) unless hash.empty? | |
end | |
end | |
module ClassMethods | |
def observe_fields(*fields, &block) | |
raise 'no fields given' if fields.empty? | |
tracked_fields[fields.map{|f| f.to_sym}] = block | |
end | |
alias :observe_field :observe_fields | |
def tracked_fields | |
@tracked_fields ||= {} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment