Class: RailsSimpleEventSourcing::Snapshot

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/rails_simple_event_sourcing/snapshot.rb

Class Method Summary collapse

Class Method Details

.create_from_event!(event) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'app/models/rails_simple_event_sourcing/snapshot.rb', line 7

def self.create_from_event!(event)
  create_or_update!(
    aggregate_type: event.eventable_type,
    aggregate_id: event.aggregate_id,
    state: event.eventable.attributes,
    version: event.version,
    schema_fingerprint: fingerprint_for(event.eventable.class)
  )
end

.create_or_update!(aggregate_type:, aggregate_id:, state:, version:, schema_fingerprint:) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'app/models/rails_simple_event_sourcing/snapshot.rb', line 17

def self.create_or_update!(aggregate_type:, aggregate_id:, state:, version:, schema_fingerprint:)
  upsert( # rubocop:disable Rails/SkipsModelValidations
    {
      aggregate_type: aggregate_type,
      aggregate_id: aggregate_id.to_s,
      state: state,
      version: version,
      schema_fingerprint: schema_fingerprint
    },
    unique_by: :index_snapshots_on_aggregate_type_and_aggregate_id
  )
end

.fingerprint_for(aggregate_class) ⇒ Object



30
31
32
33
34
35
36
# File 'app/models/rails_simple_event_sourcing/snapshot.rb', line 30

def self.fingerprint_for(aggregate_class)
  signature = aggregate_class.columns
                             .map { |c| "#{c.name}:#{c.sql_type}:#{c.null}" }
                             .sort
                             .join(',')
  Digest::SHA256.hexdigest(signature)
end