Sha256: 78bd5eb3c934c96aa21d952771dfa8e8387d3a64b2085bc0ad213c07e9f0b4e8

Contents?: true

Size: 1.85 KB

Versions: 4

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

module Dynamoid
  module Persistence
    class UpdateFields
      def self.call(*args)
        new(*args).call
      end

      def initialize(model_class, partition_key:, sort_key:, attributes:, conditions:)
        @model_class = model_class
        @partition_key = partition_key
        @sort_key = sort_key
        @attributes = attributes.symbolize_keys
        @conditions = conditions
      end

      def call
        if Dynamoid::Config.timestamps
          @attributes[:updated_at] ||= DateTime.now.in_time_zone(Time.zone)
        end

        raw_attributes = update_item
        @model_class.new(undump_attributes(raw_attributes))
      rescue Dynamoid::Errors::ConditionalCheckFailedException
      end

      private

      def update_item
        Dynamoid.adapter.update_item(@model_class.table_name, @partition_key, options_to_update_item) do |t|
          @attributes.each do |k, v|
            value_casted = TypeCasting.cast_field(v, @model_class.attributes[k])
            value_dumped = Dumping.dump_field(value_casted, @model_class.attributes[k])
            t.set(k => value_dumped)
          end
        end
      end

      def undump_attributes(attributes)
        Undumping.undump_attributes(attributes, @model_class.attributes)
      end

      def options_to_update_item
        options = {}

        if @model_class.range_key
          value_casted = TypeCasting.cast_field(@sort_key, @model_class.attributes[@model_class.range_key])
          value_dumped = Dumping.dump_field(value_casted, @model_class.attributes[@model_class.range_key])
          options[:range_key] = value_dumped
        end

        conditions = @conditions.deep_dup
        conditions[:if_exists] ||= {}
        conditions[:if_exists][@model_class.hash_key] = @partition_key
        options[:conditions] = conditions

        options
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dynamoid-3.5.0 lib/dynamoid/persistence/update_fields.rb
dynamoid-3.4.1 lib/dynamoid/persistence/update_fields.rb
dynamoid-3.4.0 lib/dynamoid/persistence/update_fields.rb
dynamoid-3.3.0 lib/dynamoid/persistence/update_fields.rb