Class: Dynamoid::Persistence::Save

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamoid/persistence/save.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, touch: nil) ⇒ Save

Returns a new instance of Save.



11
12
13
14
# File 'lib/dynamoid/persistence/save.rb', line 11

def initialize(model, touch: nil)
  @model = model
  @touch = touch # touch=false means explicit disabling of updating the `updated_at` attribute
end

Class Method Details

.call(model, **options) ⇒ Object



7
8
9
# File 'lib/dynamoid/persistence/save.rb', line 7

def self.call(model, **options)
  new(model, **options).call
end

Instance Method Details

#callObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/dynamoid/persistence/save.rb', line 16

def call
  @model.hash_key = SecureRandom.uuid if @model.hash_key.blank?

  return true unless @model.changed?

  @model.created_at ||= DateTime.now.in_time_zone(Time.zone) if @model.class.timestamps_enabled?

  if @model.class.timestamps_enabled? && !@model.updated_at_changed? && !(@touch == false && @model.persisted?)
    @model.updated_at = DateTime.now.in_time_zone(Time.zone)
  end

  # Add an optimistic locking check if the lock_version column exists
  if @model.class.attributes[:lock_version]
    @model.lock_version = (@model.lock_version || 0) + 1
  end

  if @model.new_record?
    attributes_dumped = Dumping.dump_attributes(@model.attributes, @model.class.attributes)
    Dynamoid.adapter.write(@model.class.table_name, attributes_dumped, conditions_for_write)
  else
    attributes_to_persist = @model.attributes.slice(*@model.changed.map(&:to_sym))

    Dynamoid.adapter.update_item(@model.class.table_name, @model.hash_key, options_to_update_item) do |t|
      attributes_to_persist.each do |name, value|
        value_dumped = Dumping.dump_field(value, @model.class.attributes[name])
        t.set(name => value_dumped)
      end
    end
  end

  @model.new_record = false
  true
rescue Dynamoid::Errors::ConditionalCheckFailedException => e
  if @model.new_record?
    raise Dynamoid::Errors::RecordNotUnique.new(e, @model)
  else
    raise Dynamoid::Errors::StaleObjectError.new(@model, 'persist')
  end
end