Class: PaperTrailHashDiff

Inherits:
Object
  • Object
show all
Defined in:
lib/paper_trail_hashdiff.rb

Overview

Allows storing only incremental changes in the object_changes column Uses HashDiff (github.com/liufengyun/hashdiff)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(only_objects: false) ⇒ PaperTrailHashDiff

Returns a new instance of PaperTrailHashDiff.



8
9
10
# File 'lib/paper_trail_hashdiff.rb', line 8

def initialize(only_objects: false)
  @only_objects = only_objects
end

Instance Attribute Details

#only_objectsObject (readonly)

Returns the value of attribute only_objects.



6
7
8
# File 'lib/paper_trail_hashdiff.rb', line 6

def only_objects
  @only_objects
end

Instance Method Details

#diff(changes) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/paper_trail_hashdiff.rb', line 12

def diff(changes)
  diff_changes = {}
  changes.each do |field, value_changes|
    if (
      !only_objects || (
        value_changes[0] && value_changes[1] &&
        (value_changes[0].is_a?(Hash) || value_changes[0].is_a?(Array))
      )
    )
      diff_changes[field] = Hashdiff.diff(value_changes[0], value_changes[1], array_path: true)
    else
      diff_changes[field] = value_changes
    end
  end
  diff_changes
end

#load_changeset(version) ⇒ Object



37
38
39
# File 'lib/paper_trail_hashdiff.rb', line 37

def load_changeset(version)
  HashWithIndifferentAccess.new(version.object_changes_deserialized)
end

#where_object_changes(version_model_class, attributes) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/paper_trail_hashdiff.rb', line 29

def where_object_changes(version_model_class, attributes)
  scope = version_model_class
  attributes.each do |k, v|
    scope = scope.where('(((object_changes -> ?)::jsonb ->> 0)::jsonb @> ?)', k.to_s, v.to_s)
  end
  scope
end