Sha256: 9213e023ca8e2968d62d0e7cb66f5dffda022c17ef456d981a41dd7c6c79f2d2

Contents?: true

Size: 1 KB

Versions: 3

Compression:

Stored size: 1 KB

Contents

module CouchPotato
  module Persistence
    module DirtyAttributes
      
      def self.included(base)
        base.class_eval do
          after_save :reset_dirty_attributes
        end
      end
      
      # returns true if a model has dirty attributes, i.e. their value has changed since the last save
      def dirty? 
        new? || self.class.properties.inject(false) do |res, property|
          res || property.dirty?(self)
        end
      end
      
      private
      
      def reset_dirty_attributes
        self.class.properties.each do |property|
          instance_variable_set("@#{property.name}_was", clone_attribute(send(property.name)))
        end
      end
      
      def clone_attribute(value)
        if [Fixnum, Symbol, TrueClass, FalseClass, NilClass, Float].include?(value.class)
          value
        elsif [Hash, Array].include?(value.class)
          #Deep clone
          Marshal::load(Marshal::dump(value))
        else
          value.clone
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
andrewtimberlake-couch_potato-0.2.8.2 lib/couch_potato/persistence/dirty_attributes.rb
andrewtimberlake-couch_potato-0.2.8.3 lib/couch_potato/persistence/dirty_attributes.rb
andrewtimberlake-couch_potato-0.2.8.4 lib/couch_potato/persistence/dirty_attributes.rb