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.



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

def initialize(model:, change_definition:)
  @model = model
  @change_definition = change_definition
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



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

def actor_uri
  actor_global_id_uri || fallback_global_id_uri
end

#attribute_namesObject



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

def attribute_names
  @attribute_names ||= change_definition.attribute_names.map(&:to_s)
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", {}).journal!
end

#journaled_change_for(database_operation, changes) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# 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_app_name: journaled_app_name,
    actor: actor_uri
  )
end

#relevant_attributesObject



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

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

#relevant_changesObject



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

def relevant_changes
  relevant_changes_with_previous_values.each_with_object({}) do |(k, v), result|
    result[k] = v[1]
  end
end

#updateObject



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

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