Sha256: 8b198f7e938c80eb03233950307cdc0ec0b8d8f684045056587337d001dfef81

Contents?: true

Size: 1.26 KB

Versions: 26

Compression:

Stored size: 1.26 KB

Contents

module MongoModel
  module AttributeMethods
    module Dirty
      extend ActiveSupport::Concern
      
      include ActiveModel::Dirty
      
      included do
        before_save { @previously_changed = changes }
        after_save { changed_attributes.clear }
      end
      
      def write_attribute(key, value)
        attr = key.to_sym
        
        # The attribute already has an unsaved change.
        if changed_attributes.include?(attr)
          old = changed_attributes[attr]
          changed_attributes.delete(attr) if value == old
        else
          old = clone_attribute_value(attr)
          changed_attributes[attr] = old unless value == old
        end
        
        super
      end
      
      # Returns the attributes as they were before any changes were made to the document.
      def original_attributes
        {}.with_indifferent_access.merge(attributes).merge(changed_attributes)
      end
      
    protected
      def changed_attributes
        @changed_attributes ||= {}.with_indifferent_access
      end
    
    private
      def clone_attribute_value(attribute_name)
        value = self[attribute_name.to_sym]
        value.duplicable? ? value.clone : value
      rescue TypeError, NoMethodError
        value
      end
    end
  end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
mongomodel-0.5.5 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.5.4 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.5.3 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.5.2 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.5.1 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.5.0 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.9 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.8 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.7 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.6 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.5 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.4 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.3 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.2 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.1 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.4.0 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.3.6 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.3.5 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.3.4 lib/mongomodel/concerns/attribute_methods/dirty.rb
mongomodel-0.3.3 lib/mongomodel/concerns/attribute_methods/dirty.rb