Sha256: ac7eec6612ccd00b2725261509fb3f9bbbbe0c27d239ec8a5d366284aa90dc77

Contents?: true

Size: 1.53 KB

Versions: 6

Compression:

Stored size: 1.53 KB

Contents

# encoding: UTF-8
module MongoMapper
  module Plugins
    module Dirty
      extend ActiveSupport::Concern

      include ::ActiveModel::Dirty

      def initialize(*)
        # never register initial id assignment as a change
        super.tap { changed_attributes.delete('_id') }
      end

      def initialize_from_database(*)
        super.tap { changed_attributes.clear }
      end

      def save(*)
        clear_changes { super }
      end

      def reload(*)
        super.tap { clear_changes }
      end

      protected

      def attribute_method?(attr)
        # This overrides ::ActiveSupport::Dirty#attribute_method? to allow attributes to be any key
        # in the attributes hash ( default ) or any key defined on the model that may not yet have
        # had a value stored in the attributes collection.
        super || key_names.include?(attr)
      end

      def clear_changes
        previous = changes
        (block_given? ? yield : true).tap do |result|
          unless result == false #failed validation; nil is OK.
            @previously_changed = previous
            changed_attributes.clear
          end
        end
      end

      private

      def write_key(key, value)
        key = key.to_s
        attribute_will_change!(key) unless attribute_changed?(key)
        super(key, value).tap do
          changed_attributes.delete(key) unless attribute_value_changed?(key)
        end
      end

      def attribute_value_changed?(key_name)
        attribute_was(key_name) != read_key(key_name)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 3 rubygems

Version Path
mongo_mapper-0.12.0 lib/mongo_mapper/plugins/dirty.rb
lookout-mongo_mapper-0.11.3 lib/mongo_mapper/plugins/dirty.rb
mongo_mapper-0.11.2 lib/mongo_mapper/plugins/dirty.rb
jamieorc-mongo_mapper-0.11.1.1 lib/mongo_mapper/plugins/dirty.rb
mongo_mapper-0.11.1 lib/mongo_mapper/plugins/dirty.rb
mongo_mapper-0.11.0 lib/mongo_mapper/plugins/dirty.rb