Sha256: f086470f28e025145c7b90a7c0cb8cda3a38a8f2308e1792ebcdebd2e5826604

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 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
        # Chaining super into tap breaks implicit block passing in Ruby 1.8
        doc = super
        doc.tap { changed_attributes.delete('_id') }
      end

      def save(*)
        clear_changes { super }
      end

      def reload(*)
        doc = super
        doc.tap { clear_changes }
      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

    protected

      # We don't call super here to avoid invoking #attributes, which builds a whole new hash per call.
      def attribute_method?(attr_name)
        keys.key?(attr_name) || !embedded_associations.detect {|a| a.name == attr_name }.nil?
      end

    private

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

      def attribute_value_changed?(key_name)
        changed_attributes[key_name] != read_key(key_name)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mongo_mapper-0.14.0 lib/mongo_mapper/plugins/dirty.rb
mongo_mapper-0.14.0.rc1 lib/mongo_mapper/plugins/dirty.rb