Class: Dynamoid::TransactionWrite::Create

Inherits:
Action
  • Object
show all
Defined in:
lib/dynamoid/transaction_write/create.rb

Constant Summary

Constants inherited from Action

Action::VALID_OPTIONS

Instance Attribute Summary

Attributes inherited from Action

#additions, #attributes, #deletions, #model, #options, #removals

Instance Method Summary collapse

Methods inherited from Action

#add, #add_timestamps, #changes_applied, #delete, #find_from_attributes, #hash_key, #model_class, #raise_validation_error?, #range_key, #sanitize_item, #set, #skip_callbacks?, #skip_validation?, #touch_model_timestamps, #valid?, #write_attributes_to_model

Constructor Details

#initialize(model_or_model_class, attributes = {}, options = {}) ⇒ Create

model is created if not otherwise specified so callbacks can be run



9
10
11
12
13
14
15
16
17
18
# File 'lib/dynamoid/transaction_write/create.rb', line 9

def initialize(model_or_model_class, attributes = {}, options = {})
  model = if model_or_model_class.is_a?(Dynamoid::Document)
            model_or_model_class
          else
            model_or_model_class.new(attributes)
          end
  super(model, attributes, options)

  # don't initialize hash key here, callbacks haven't run yet
end

Instance Method Details

#run_callbacksObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/dynamoid/transaction_write/create.rb', line 20

def run_callbacks
  # model always exists
  model.run_callbacks(:save) do
    model.run_callbacks(:create) do
      model.run_callbacks(:validate) do
        yield if block_given?
      end
    end
  end
end

#to_hObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dynamoid/transaction_write/create.rb', line 31

def to_h
  model.hash_key = SecureRandom.uuid if model.hash_key.blank?
  write_attributes_to_model
  touch_model_timestamps
  # model always exists
  item = Dynamoid::Dumping.dump_attributes(model.attributes, model_class.attributes)

  condition = "attribute_not_exists(#{model_class.hash_key})"
  condition += " and attribute_not_exists(#{model_class.range_key})" if model_class.range_key? # needed?
  result = {
    put: {
      item: sanitize_item(item),
      table_name: model_class.table_name,
    }
  }
  result[:put][:condition_expression] = condition unless options[:skip_existence_check]

  result
end