Skip to content

Instantly share code, notes, and snippets.

@kronos
Created June 14, 2011 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kronos/1024686 to your computer and use it in GitHub Desktop.
Save kronos/1024686 to your computer and use it in GitHub Desktop.
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