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.



6
7
8
9
10
# File 'app/models/journaled/change_writer.rb', line 6

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.



2
3
4
# File 'app/models/journaled/change_writer.rb', line 2

def change_definition
  @change_definition
end

#modelObject (readonly)

Returns the value of attribute model.



2
3
4
# File 'app/models/journaled/change_writer.rb', line 2

def model
  @model
end

Instance Method Details

#actor_uriObject



49
50
51
# File 'app/models/journaled/change_writer.rb', line 49

def actor_uri
  @actor_uri ||= Journaled.actor_uri
end

#createObject



12
13
14
# File 'app/models/journaled/change_writer.rb', line 12

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

#deleteObject



20
21
22
# File 'app/models/journaled/change_writer.rb', line 20

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

#journaled_change_for(database_operation, changes) ⇒ Object



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

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



37
38
39
# File 'app/models/journaled/change_writer.rb', line 37

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

#relevant_changed_attributesObject



45
46
47
# File 'app/models/journaled/change_writer.rb', line 45

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

#relevant_unperturbed_attributesObject



41
42
43
# File 'app/models/journaled/change_writer.rb', line 41

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

#updateObject



16
17
18
# File 'app/models/journaled/change_writer.rb', line 16

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