Module: Mara::Model::Persistence

Included in:
Base
Defined in:
lib/mara/model/persistence.rb

Overview

Methods that save/update/delete a model.

Author:

  • Maddie Schipper

Since:

  • 1.0.0

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

Since:

  • 1.0.0



15
16
17
# File 'lib/mara/model/persistence.rb', line 15

def self.included(klass)
  klass.extend(ClassMethods)
end

Instance Method Details

#destroytrue, false

Perform a destroy on the model.

Returns:

  • (true, false)

Since:

  • 1.0.0



99
100
101
102
103
# File 'lib/mara/model/persistence.rb', line 99

def destroy
   Mara.instrument('model.destroy', model: self) do
     Mara::Batch.delete_model(primary_key)
  end
end

#destroy!void

Note:

Same as #destroy but will raise an error on delete failure.

This method returns an undefined value.

Perform a destroy on the model.

See Also:

Since:

  • 1.0.0



113
114
115
116
117
# File 'lib/mara/model/persistence.rb', line 113

def destroy!
   Mara.instrument('model.destroy', model: self) do
     Mara::Batch.delete_model!(primary_key)
  end
end

#primary_keyHash

Get a primary key attribute for the item.

Returns:

  • (Hash)

Since:

  • 1.0.0



47
48
49
50
51
52
53
54
55
# File 'lib/mara/model/persistence.rb', line 47

def primary_key
  {}.tap do |base|
    base[self.class.partition_key] =  Mara::AttributeFormatter.format(partition_key)

    unless self.class.sort_key.blank?
      base[self.class.sort_key] =  Mara::AttributeFormatter.format(sort_key)
    end
  end
end

#savetrue, false

Perform validation and save the model.

Returns:

  • (true, false)

Since:

  • 1.0.0



71
72
73
74
75
76
77
# File 'lib/mara/model/persistence.rb', line 71

def save
   Mara.instrument('model.save', model: self) do
    next false unless valid?

     Mara::Batch.save_model(to_item)
  end
end

#save!void

Note:

Same as #save but will raise an error on validation faiure and save failure

This method returns an undefined value.

Perform validation and save the model.

See Also:

Since:

  • 1.0.0



88
89
90
91
92
93
# File 'lib/mara/model/persistence.rb', line 88

def save!
   Mara.instrument('model.save', model: self) do
    validate!
     Mara::Batch.save_model!(to_item)
  end
end

#to_dynamoHash

Converts the attributes into a DynamoDB compatable hash.

Returns:

  • (Hash)

Since:

  • 1.0.0



33
34
35
36
37
38
39
# File 'lib/mara/model/persistence.rb', line 33

def to_dynamo
  {}.tap do |formatted|
    attributes.each do |key, value|
      formatted[key] =  Mara::AttributeFormatter.format(value)
    end
  end
end

#to_itemHash

Create a DynamoDB representation of the model.

Returns:

  • (Hash)

Since:

  • 1.0.0



63
64
65
# File 'lib/mara/model/persistence.rb', line 63

def to_item
  to_dynamo.merge(primary_key)
end