Class: Journaled::ChangeWriter

Inherits:
Object
  • Object
show all
Defined in:
app/models/journaled/change_writer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, change_definition:) ⇒ ChangeWriter

Returns a new instance of ChangeWriter.



8
9
10
11
12
# File 'app/models/journaled/change_writer.rb', line 8

def initialize(model:, change_definition:)
  @model = model
  @change_definition = change_definition
  change_definition.validate!(model) unless change_definition.validated?
end

Instance Attribute Details

#change_definitionObject (readonly)

Returns the value of attribute change_definition.



4
5
6
# File 'app/models/journaled/change_writer.rb', line 4

def change_definition
  @change_definition
end

#modelObject (readonly)

Returns the value of attribute model.



4
5
6
# File 'app/models/journaled/change_writer.rb', line 4

def model
  @model
end

Instance Method Details

#actor_uriObject



51
52
53
# File 'app/models/journaled/change_writer.rb', line 51

def actor_uri
  @actor_uri ||= Journaled.actor_uri
end

#createObject



14
15
16
# File 'app/models/journaled/change_writer.rb', line 14

def create
  journaled_change_for("create", relevant_attributes).journal!
end

#deleteObject



22
23
24
# File 'app/models/journaled/change_writer.rb', line 22

def delete
  journaled_change_for("delete", relevant_unperturbed_attributes).journal!
end

#journaled_change_for(database_operation, changes) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/models/journaled/change_writer.rb', line 26

def journaled_change_for(database_operation, changes)
  Journaled::Change.new(
    table_name: model.class.table_name,
    record_id: model.id.to_s,
    database_operation: database_operation,
    logical_operation: logical_operation,
    changes: JSON.dump(changes),
    journaled_stream_name: journaled_stream_name,
    journaled_enqueue_opts: model.journaled_enqueue_opts,
    actor: actor_uri,
  )
end

#relevant_attributesObject



39
40
41
# File 'app/models/journaled/change_writer.rb', line 39

def relevant_attributes
  model.attributes.slice(*attribute_names)
end

#relevant_changed_attributesObject



47
48
49
# File 'app/models/journaled/change_writer.rb', line 47

def relevant_changed_attributes
  pluck_changed_values(model.saved_changes.slice(*attribute_names), index: 1)
end

#relevant_unperturbed_attributesObject



43
44
45
# File 'app/models/journaled/change_writer.rb', line 43

def relevant_unperturbed_attributes
  model.attributes.merge(pluck_changed_values(model.changes, index: 0)).slice(*attribute_names)
end

#updateObject



18
19
20
# File 'app/models/journaled/change_writer.rb', line 18

def update
  journaled_change_for("update", relevant_changed_attributes).journal! if relevant_changed_attributes.present?
end