Module: Dynamoid::Persistence::ClassMethods

Defined in:
lib/dynamoid/persistence.rb

Instance Method Summary collapse

Instance Method Details

#create_table(options = {}) ⇒ Object

Creates a table.

Parameters:

  • options (Hash) (defaults to: {})

    options to pass for table creation

Options Hash (options):

  • :id (Symbol)

    the id field for the table

  • :table_name (Symbol)

    the actual name for the table

  • :read_capacity (Integer)

    set the read capacity for the table; does not work on existing tables

  • :write_capacity (Integer)

    set the write capacity for the table; does not work on existing tables

  • {range_key (Hash)

    > :type} a hash of the name of the range key and a symbol of its type

  • :hash_key_type (Symbol)

    the dynamo type of the hash key (:string or :number)

Since:

  • 0.4.0



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/dynamoid/persistence.rb', line 37

def create_table(options = {})
  if self.range_key
    range_key_hash = { range_key => dynamo_type(attributes[range_key][:type]) }
  else
    range_key_hash = nil
  end
  options = {
    id: self.hash_key,
    table_name: self.table_name,
    write_capacity: self.write_capacity,
    read_capacity: self.read_capacity,
    range_key: range_key_hash,
    hash_key_type: dynamo_type(attributes[self.hash_key][:type]),
    local_secondary_indexes: self.local_secondary_indexes.values,
    global_secondary_indexes: self.global_secondary_indexes.values
  }.merge(options)

  Dynamoid.adapter.create_table(options[:table_name], options[:id], options)
end

#delete_tableObject

Deletes the table for the model



58
59
60
# File 'lib/dynamoid/persistence.rb', line 58

def delete_table
  Dynamoid.adapter.delete_table(self.table_name)
end

#dump_field(value, options) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/dynamoid/persistence.rb', line 155

def dump_field(value, options)
  if (field_class = options[:type]).is_a?(Class)
    if value.respond_to?(:dynamoid_dump)
      value.dynamoid_dump
    elsif field_class.respond_to?(:dynamoid_dump)
      field_class.dynamoid_dump(value)
    else
      raise ArgumentError, "Neither #{field_class} nor #{value} support serialization for Dynamoid."
    end
  else
    case options[:type]
      when :string
        !value.nil? ? value.to_s : nil
      when :integer
        !value.nil? ? Integer(value) : nil
      when :number
        !value.nil? ? value : nil
      when :set
        !value.nil? ? Set.new(value) : nil
      when :array
        !value.nil? ? value : nil
      when :datetime
        !value.nil? ? format_datetime(value, options) : nil
      when :date
        !value.nil? ? format_date(value, options) : nil
      when :serialized
        options[:serializer] ? options[:serializer].dump(value) : value.to_yaml
      when :raw
        !value.nil? ? value : nil
      when :boolean
        if !value.nil?
          if options[:store_as_native_boolean]
            !!value # native boolean type
          else
            value.to_s[0] # => "f" or "t"
          end
        else
          nil
        end
      else
        raise ArgumentError, "Unknown type #{options[:type]}"
    end
  end
end

#dynamo_type(type) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/dynamoid/persistence.rb', line 200

def dynamo_type(type)
  if type.is_a?(Class)
    type.respond_to?(:dynamoid_field_type) ? type.dynamoid_field_type : :string
  else
    case type
      when :integer, :number, :datetime, :date
        :number
      when :string, :serialized
        :string
      else
        raise 'unknown type'
    end
  end
end

#from_database(attrs = {}) ⇒ Object



62
63
64
65
# File 'lib/dynamoid/persistence.rb', line 62

def from_database(attrs = {})
  clazz = attrs[:type] ? obj = attrs[:type].constantize : self
  clazz.new(attrs).tap { |r| r.new_record = false }
end

#import(objects) ⇒ Object

Creates several models at once. Neither callbacks nor validations run. It works efficiently because of using BatchWriteItem.

Returns array of models

Uses backoff specified by ‘Dynamoid::Config.backoff` config option

Examples:

User.import([{ name: 'a' }, { name: 'b' }])

Parameters:

  • items (Array<Hash>)


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/dynamoid/persistence.rb', line 227

def import(objects)
  documents = objects.map do |attrs|
    self.build(attrs).tap do |item|
      item.hash_key = SecureRandom.uuid if item.hash_key.blank?
    end
  end

  unless Dynamoid.config.backoff
    Dynamoid.adapter.batch_write_item(self.table_name, documents.map(&:dump))
  else
    backoff = nil
    Dynamoid.adapter.batch_write_item(self.table_name, documents.map(&:dump)) do |has_unprocessed_items|
      if has_unprocessed_items
        backoff ||= Dynamoid.config.build_backoff
        backoff.call
      else
        backoff = nil
      end
    end
  end

  documents.each { |d| d.new_record = false }
  documents
end

#table_nameObject



20
21
22
23
24
25
# File 'lib/dynamoid/persistence.rb', line 20

def table_name
  table_base_name = options[:name] || base_class.name.split('::').last
    .downcase.pluralize

  @table_name ||= [Dynamoid::Config.namespace.to_s, table_base_name].reject(&:empty?).join('_')
end

#undump(incoming = nil) ⇒ Object

Undump an object into a hash, converting each type from a string representation of itself into the type specified by the field.

Since:

  • 0.2.0



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/dynamoid/persistence.rb', line 70

def undump(incoming = nil)
  incoming = (incoming || {}).symbolize_keys
  Hash.new.tap do |hash|
    self.attributes.each do |attribute, options|
      if incoming.has_key?(attribute)
        hash[attribute] = undump_field(incoming[attribute], options)
      elsif options.has_key?(:default)
        hash[attribute] = evaluate_default_value(options[:default])
      else
        hash[attribute] = nil
      end
    end
    incoming.each {|attribute, value| hash[attribute] = value unless hash.has_key? attribute }
  end
end

#undump_field(value, options) ⇒ Object

Undump a string value for a given type.

Since:

  • 0.2.0



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/dynamoid/persistence.rb', line 89

def undump_field(value, options)
  if (field_class = options[:type]).is_a?(Class)
    raise 'Dynamoid class-type fields do not support default values' if options[:default]

    if field_class.respond_to?(:dynamoid_load)
      field_class.dynamoid_load(value)
    end
  elsif options[:type] == :serialized
    if value.is_a?(String)
      options[:serializer] ? options[:serializer].load(value) : YAML.load(value)
    else
      value
    end
  else
    unless value.nil?
      case options[:type]
        when :string
          value.to_s
        when :integer
          Integer(value)
        when :number
          BigDecimal.new(value.to_s)
        when :array
          value.to_a
        when :raw
          if value.is_a?(Hash)
            undump_hash(value)
          else
            value
          end
        when :set
          undump_set(options, value)
        when :datetime
          parse_datetime(value, options)
        when :date
          if value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time)
            value.to_date
          else
            parse_date(value, options)
          end
        when :boolean
          if value == 't' || value == true
            true
          elsif value == 'f' || value == false
            false
          else
            raise ArgumentError, 'Boolean column neither true nor false'
          end
        else
          raise ArgumentError, "Unknown type #{options[:type]}"
      end
    end
  end
end

#undump_set(options, value) ⇒ Object



144
145
146
147
148
149
150
151
152
153
# File 'lib/dynamoid/persistence.rb', line 144

def undump_set(options, value)
  case options[:of]
  when :integer
    value.map { |v| Integer(v) }.to_set
  when :number
    value.map { |v| BigDecimal.new(v.to_s) }.to_set
  else
    value.is_a?(Set) ? value : Set.new(value)
  end
end