Class: ActiveItem::Base

Inherits:
Object
  • Object
show all
Extended by:
DatabaseHelpers, QueryHelpers, Validations, ActiveModel::Callbacks
Includes:
Associations, ComposedOf, Logging, ActiveModel::Dirty, ActiveModel::Validations
Defined in:
lib/active_item/base.rb

Overview

Base class for all ActiveItem models. Provides persistence, callbacks, validations, dirty tracking, and an ActiveRecord-like interface for DynamoDB tables.

Constant Summary

Constants included from QueryHelpers

QueryHelpers::RECENT_INDEX

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DatabaseHelpers

exists?, get, put, query, scan

Methods included from QueryHelpers

all, all_records, batch_find, batch_write, count, delete_all, destroy_all, exists?, find, find_by, first, includes, indexes, last, none, recent, where

Methods included from Validations

validates_uniqueness_of

Methods included from Associations

#check_dependent_associations

Methods included from ModelLoader

#safe_constantize_model

Methods included from ComposedOf

#populate_composed_attributes_from_item

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/active_item/base.rb', line 44

def initialize(attributes = {})
  @_preloaded_counts = {}
  @_preloaded_associations = {}
  @new_record = true

  return unless attributes.is_a?(Hash)

  attributes.each do |key, value|
    setter = "#{key}="
    send(setter, value) if respond_to?(setter)
  end

  clear_changes_information
end

Class Attribute Details

.dynamodbObject



136
137
138
# File 'lib/active_item/base.rb', line 136

def dynamodb
  @dynamodb ||= Aws::DynamoDB::Client.new(http_wire_trace: false)
end

Instance Attribute Details

#created_atObject

Returns the value of attribute created_at.



34
35
36
# File 'lib/active_item/base.rb', line 34

def created_at
  @created_at
end

#dbrecordObject

Returns the value of attribute dbrecord.



34
35
36
# File 'lib/active_item/base.rb', line 34

def dbrecord
  @dbrecord
end

#idObject

Returns the value of attribute id.



33
34
35
# File 'lib/active_item/base.rb', line 33

def id
  @id
end

#updated_atObject

Returns the value of attribute updated_at.



34
35
36
# File 'lib/active_item/base.rb', line 34

def updated_at
  @updated_at
end

Class Method Details

._scopesObject



242
243
244
# File 'lib/active_item/base.rb', line 242

def _scopes
  @_scopes ||= {}
end

.after_save(*args) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/active_item/base.rb', line 222

def after_save(*args, &)
  options = args.extract_options!
  if options[:on]
    case options[:on].to_sym
    when :create then set_callback(:create, :after, *args, &)
    when :update then set_callback(:update, :after, *args, &)
    else raise ArgumentError, "Invalid on: option '#{options[:on]}'. Must be :create or :update"
    end
  else
    set_callback(:save, :after, *args, &)
  end
end

.attr_accessor(*attrs) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/active_item/base.rb', line 96

def attr_accessor(*attrs)
  attrs.each do |attr|
    attr_name = attr.to_s

    define_attribute_methods attr_name

    define_method(attr_name) do
      instance_variable_get("@#{attr_name}")
    end

    define_method("#{attr_name}=") do |value|
      old_value = instance_variable_get("@#{attr_name}")
      send("#{attr_name}_will_change!") if (old_value != value) && !changed_attributes.key?(attr_name)
      instance_variable_set("@#{attr_name}", value)
    end
  end
end

.attribute_namesObject



67
68
69
# File 'lib/active_item/base.rb', line 67

def self.attribute_names
  @attribute_names ||= instance_methods.grep(/\A[a-z_][a-z0-9_]*=\z/).map { |m| m.to_s.chomp('=') }.sort
end

.before_save(*args) ⇒ Object

Callback DSL — :on option routes before_save/after_save to create/update



209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/active_item/base.rb', line 209

def before_save(*args, &)
  options = args.extract_options!
  if options[:on]
    case options[:on].to_sym
    when :create then set_callback(:create, :before, *args, &)
    when :update then set_callback(:update, :before, *args, &)
    else raise ArgumentError, "Invalid on: option '#{options[:on]}'. Must be :create or :update"
    end
  else
    set_callback(:save, :before, *args, &)
  end
end

.const_missing(name) ⇒ Object



23
24
25
# File 'lib/active_item/base.rb', line 23

def self.const_missing(name)
  ActiveItem.const_defined?(name) ? ActiveItem.const_get(name) : super
end

.create(attributes = {}) ⇒ Object



379
380
381
382
383
# File 'lib/active_item/base.rb', line 379

def self.create(attributes = {})
  obj = new(attributes)
  obj.save
  obj
end

.create!(attributes = {}) ⇒ Object



385
386
387
388
389
# File 'lib/active_item/base.rb', line 385

def self.create!(attributes = {})
  obj = new(attributes)
  obj.save!
  obj
end

.dynamo_attribute_map(mappings = nil) ⇒ Object



142
143
144
145
146
147
148
# File 'lib/active_item/base.rb', line 142

def dynamo_attribute_map(mappings = nil)
  if mappings
    @dynamo_attribute_map = mappings.transform_keys(&:to_s)
  else
    @dynamo_attribute_map || {}
  end
end

.dynamo_key_variants(attr_name) ⇒ Object



165
166
167
168
169
170
# File 'lib/active_item/base.rb', line 165

def dynamo_key_variants(attr_name)
  attr_str = attr_name.to_s
  primary_key = to_dynamo_key(attr_str)
  camel_case = attr_str.camelize(:lower)
  [primary_key, camel_case, attr_str].uniq
end

.find_or_create_by(attributes, &block) ⇒ Object



198
199
200
201
202
203
204
205
206
# File 'lib/active_item/base.rb', line 198

def find_or_create_by(attributes, &block)
  record = find_by(**attributes)
  return record if record

  record = new(**attributes)
  block.call(record) if block_given?
  record.save
  record
end

.from_dynamo_key(dynamo_key) ⇒ Object



157
158
159
160
161
162
163
# File 'lib/active_item/base.rb', line 157

def from_dynamo_key(dynamo_key)
  key_str = dynamo_key.to_s
  reverse_map = dynamo_attribute_map.invert
  return reverse_map[key_str] if reverse_map.key?(key_str)

  key_str.underscore
end

.instantiate(item) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/active_item/base.rb', line 172

def instantiate(item)
  normalized_item = normalize_dynamodb_values(item)

  record = allocate
  record.instance_variable_set(:@id, normalized_item[primary_key])
  record.send(:populate_attributes_from_item, normalized_item)
  record.instance_variable_set(:@new_record, false)
  record.instance_variable_set(:@mutations_from_database, nil)
  record.instance_variable_set(:@dbrecord, normalized_item)
  record.send(:clear_changes_information)
  record
end

.normalize_dynamodb_values(obj) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/active_item/base.rb', line 185

def normalize_dynamodb_values(obj)
  case obj
  when BigDecimal
    obj.frac.zero? ? obj.to_i : obj.to_f
  when Hash
    obj.transform_values { |v| normalize_dynamodb_values(v) }
  when Array
    obj.map { |v| normalize_dynamodb_values(v) }
  else
    obj
  end
end

.primary_keyObject



114
115
116
# File 'lib/active_item/base.rb', line 114

def primary_key
  @primary_key ||= 'id'
end

.primary_key=(value) ⇒ Object



118
119
120
121
122
123
124
125
126
# File 'lib/active_item/base.rb', line 118

def primary_key=(value)
  remove_method primary_key.to_sym
  remove_method :"#{primary_key}="

  @primary_key = value.to_s

  alias_method primary_key.to_sym, :id
  alias_method :"#{primary_key}=", :id=
end

.scope(name, body) ⇒ Object

Raises:

  • (ArgumentError)


235
236
237
238
239
240
# File 'lib/active_item/base.rb', line 235

def scope(name, body)
  raise ArgumentError, 'scope body must be callable (Proc/Lambda)' unless body.respond_to?(:call)

  _scopes[name.to_sym] = body
  define_singleton_method(name) { all.instance_exec(&body) }
end

.table_nameObject



128
129
130
# File 'lib/active_item/base.rb', line 128

def table_name
  @table_name || default_table_name
end

.table_name=(value) ⇒ Object



132
133
134
# File 'lib/active_item/base.rb', line 132

def table_name=(value)
  @table_name = value.to_s
end

.to_dynamo_key(attr_name) ⇒ Object



150
151
152
153
154
155
# File 'lib/active_item/base.rb', line 150

def to_dynamo_key(attr_name)
  attr_str = attr_name.to_s
  return dynamo_attribute_map[attr_str] if dynamo_attribute_map.key?(attr_str)

  attr_str.camelize(:lower)
end

.transaction {|Transaction| ... } ⇒ Object

Execute a block within a transaction context.

Supports two usage patterns:

  1. Explicit API (block receives transaction):

    Model.transaction do |txn|
    txn.put(record1)
    txn.update(record2)
    end
    
  2. Implicit API (transactional saves):

    Model.transaction do
    record1.save!
    record2.save!
    record3.destroy!
    end
    

In the implicit API, save/destroy calls are automatically enrolled. The transaction is committed when the block completes successfully. If an exception is raised, no changes are committed (all-or-nothing).

Yields:

Raises:



414
415
416
417
418
419
420
421
422
423
424
# File 'lib/active_item/base.rb', line 414

def self.transaction
  txn = Transaction.new
  Transaction.current = txn
  begin
    # Support both explicit (yield txn) and implicit (no block param) APIs
    yield txn if block_given?
    txn.execute!
  ensure
    Transaction.current = nil
  end
end

.transaction_find(items) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/active_item/base.rb', line 426

def self.transaction_find(items)
  return [] if items.empty?
  raise TransactionError, "DynamoDB transactions are limited to 100 items (got #{items.length})" if items.length > 100

  transact_items = items.map do |item|
    { get: { table_name: item[:model].table_name, key: { item[:model].primary_key.to_s => item[:key] } } }
  end

  client = items.first[:model].dynamodb
  response = client.transact_get_items(transact_items: transact_items)

  response.responses.each_with_index.map do |resp, idx|
    items[idx][:model].instantiate(resp.item) if resp.item
  end
rescue Aws::DynamoDB::Errors::TransactionCanceledException => e
  raise TransactionError, "Transaction read cancelled: #{e.message}"
end

Instance Method Details

#_preloaded_associationsObject



63
64
65
# File 'lib/active_item/base.rb', line 63

def _preloaded_associations
  @_preloaded_associations ||= {}
end

#_preloaded_countsObject



59
60
61
# File 'lib/active_item/base.rb', line 59

def _preloaded_counts
  @_preloaded_counts ||= {}
end

#assign_attributes(attributes) ⇒ Object



474
475
476
477
478
479
# File 'lib/active_item/base.rb', line 474

def assign_attributes(attributes)
  attributes.each do |key, value|
    setter = "#{key}="
    send(setter, value) if respond_to?(setter)
  end
end

#attribute_changed?(attr_name) ⇒ Boolean

Returns:

  • (Boolean)


481
482
483
# File 'lib/active_item/base.rb', line 481

def attribute_changed?(attr_name)
  super(attr_name.to_s)
end

#attribute_was(attr_name) ⇒ Object



485
486
487
# File 'lib/active_item/base.rb', line 485

def attribute_was(attr_name)
  changed_attributes[attr_name.to_s]
end

#attributesObject



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/active_item/base.rb', line 299

def attributes
  attrs = {}
  pk_name = self.class.primary_key
  pk_value = begin
    send(pk_name)
  rescue StandardError
    instance_variable_get("@#{pk_name}")
  end
  attrs['id'] = pk_value
  attrs[pk_name] = pk_value

  self.class.attribute_names.each do |attr_name|
    next if attr_name == 'dbrecord'

    value = instance_variable_get("@#{attr_name}")
    attrs[attr_name] = value unless value.nil?
  end

  attrs['created_at'] = @created_at
  attrs['updated_at'] = @updated_at
  attrs
end

#deleteObject



466
467
468
469
470
471
472
# File 'lib/active_item/base.rb', line 466

def delete
  perform_destroy
  true
rescue StandardError => e
  dynamo_logger.error("Failed to delete #{self.class.name}: #{e.message}")
  false
end

#destroyObject



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/active_item/base.rb', line 444

def destroy
  # If inside a transaction block, enroll this destroy in the transaction
  return enroll_destroy_in_transaction if Transaction.active?

  result = run_callbacks(:destroy) { perform_destroy }
  return false if result == false

  true
rescue DeleteRestrictionError
  false
rescue StandardError => e
  dynamo_logger.error("Failed to destroy #{self.class.name}: #{e.message}")
  errors.add(:base, e.message)
  false
end

#destroy!Object

Raises:



460
461
462
463
464
# File 'lib/active_item/base.rb', line 460

def destroy!
  raise RecordNotDestroyed.new(nil, self) unless destroy

  true
end

#has_changes_to_save?Boolean

Returns:

  • (Boolean)


291
292
293
# File 'lib/active_item/base.rb', line 291

def has_changes_to_save?
  changed?
end

#inspectObject



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/active_item/base.rb', line 322

def inspect
  begin
    send(self.class.primary_key)
  rescue StandardError
    id
  end
  attr_strs = self.class.attribute_names.filter_map do |attr|
    next if attr == 'dbrecord'

    value = instance_variable_get("@#{attr}")
    next if value.nil?

    "#{attr}: #{value.inspect}"
  end
  "#<#{self.class.name} #{attr_strs.join(', ')}>"
end

#new_record?Boolean

Returns:

  • (Boolean)


263
264
265
# File 'lib/active_item/base.rb', line 263

def new_record?
  @new_record != false
end

#persisted?Boolean

Returns:

  • (Boolean)


267
268
269
# File 'lib/active_item/base.rb', line 267

def persisted?
  !new_record?
end

#populate_attributes_from_item(item) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/active_item/base.rb', line 71

def populate_attributes_from_item(item)
  self.class.attribute_names.each do |attr_name|
    next if attr_name == 'id'

    value = nil
    found = false
    self.class.dynamo_key_variants(attr_name).each do |key|
      next unless item.key?(key)

      value = item[key]
      found = true
      break
    end

    instance_variable_set("@#{attr_name}", value) if found
  end

  @created_at = item['createdAt'] || item['created_at']
  @updated_at = item['updatedAt'] || item['updated_at']

  populate_custom_attributes_from_item(item) if respond_to?(:populate_custom_attributes_from_item, true)
  populate_composed_attributes_from_item(item) if self.class.respond_to?(:compositions) && self.class.compositions.any?
end

#reloadObject



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/active_item/base.rb', line 271

def reload
  raise 'Cannot reload a new record' if new_record?

  fresh_record = self.class.find(id)
  raise "Record not found: #{self.class.name} with id #{id}" unless fresh_record

  self.class.attribute_names.each do |attr_name|
    next if attr_name == 'dbrecord'

    value = fresh_record.instance_variable_get("@#{attr_name}")
    instance_variable_set("@#{attr_name}", value)
  end

  @created_at = fresh_record.created_at
  @updated_at = fresh_record.updated_at
  @dbrecord = fresh_record.dbrecord
  clear_changes_information
  self
end

#save(validate: true) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/active_item/base.rb', line 349

def save(validate: true)
  return false if validate && !run_validations

  # If inside a transaction block, enroll this save in the transaction
  return enroll_in_transaction if Transaction.active?

  result = run_callbacks :save do
    if new_record?
      run_callbacks(:create) { perform_create }
    else
      run_callbacks(:update) { perform_update }
    end
  end

  return false if result == false

  changes_applied
  @new_record = false
  true
rescue StandardError => e
  dynamo_logger.error("Failed to save #{self.class.name}: #{e.message}")
  raise e
end

#save!Object

Raises:



373
374
375
376
377
# File 'lib/active_item/base.rb', line 373

def save!
  raise RecordInvalid.new(self), "Validation failed: #{errors.full_messages.join(', ')}" unless save

  true
end

#to_hObject



295
296
297
# File 'lib/active_item/base.rb', line 295

def to_h
  attributes.with_indifferent_access
end

#update(attributes) ⇒ Object



339
340
341
342
# File 'lib/active_item/base.rb', line 339

def update(attributes)
  assign_attributes(attributes)
  save
end

#update!(attributes) ⇒ Object



344
345
346
347
# File 'lib/active_item/base.rb', line 344

def update!(attributes)
  assign_attributes(attributes)
  save!
end

#valid?(context = nil) ⇒ Boolean

Returns:

  • (Boolean)


489
490
491
492
493
494
495
496
497
498
# File 'lib/active_item/base.rb', line 489

def valid?(context = nil)
  return super if defined?(@running_validations) && @running_validations

  @running_validations = true
  begin
    run_callbacks(:validation) { super(context) }
  ensure
    @running_validations = false
  end
end