Sha256: f62cd4c176931b08205d2d4105460f2a7c6e7ab6090a8255fdc7c8624949384c

Contents?: true

Size: 1.56 KB

Versions: 5

Compression:

Stored size: 1.56 KB

Contents

# encoding: utf-8
module Mongoid
  module Persistable

    # Defines behaviour for $set operations.
    #
    # @since 4.0.0
    module Settable
      extend ActiveSupport::Concern

      # Perform a $set operation on the provided field/value pairs and set the
      # values in the document in memory.
      #
      # @example Set the values.
      #   document.set(title: "sir", dob: Date.new(1970, 1, 1))
      #
      # @param [ Hash ] setters The field/value pairs to set.
      #
      # @return [ Document ] The document.
      #
      # @since 4.0.0
      def set(setters)
        prepare_atomic_operation do |ops|
          process_atomic_operations(setters) do |field, value|

            field_and_value_hash = hasherizer(field.split('.'), value)
            field = field_and_value_hash.keys.first.to_s
            value = field_and_value_hash[field]

            if fields[field] && fields[field].type == Hash && attributes.key?(field) && Hash === value && !value.empty?
              merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
              value = (attributes[field] || {}).merge(value, &merger)
            end

            process_attribute(field.to_s, value)

            unless relations.include?(field.to_s)
              ops[atomic_attribute_name(field)] = attributes[field]
            end
          end
          { "$set" => ops } unless ops.empty?
        end
      end
    end

    def hasherizer(keys, value)
      return value if keys.empty?
      {}.tap { |hash| hash[keys.shift] = hasherizer(keys, value) }
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mongoid-6.4.8 lib/mongoid/persistable/settable.rb
mongoid-6.4.7 lib/mongoid/persistable/settable.rb
mongoid-6.4.5 lib/mongoid/persistable/settable.rb
mongoid-6.4.4 lib/mongoid/persistable/settable.rb
mongoid-6.4.2 lib/mongoid/persistable/settable.rb