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
9
# File 'app/models/journaled/change_writer.rb', line 5

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



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

def actor_uri
  @actor_uri ||= Journaled.actor_uri
end

#createObject



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

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

#deleteObject



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

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

#journaled_change_for(database_operation, changes) ⇒ Object



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

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



35
36
37
# File 'app/models/journaled/change_writer.rb', line 35

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

#relevant_changed_attributesObject



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

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

#relevant_unperturbed_attributesObject



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

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

#updateObject



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

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