Module: Glib::Snapshot

Extended by:
ActiveSupport::Concern
Defined in:
lib/glib/snapshot.rb

Instance Method Summary collapse

Instance Method Details

#associations_for_snapshotObject



234
235
236
# File 'lib/glib/snapshot.rb', line 234

def associations_for_snapshot
  children_to_snapshot.keys.filter { |key| respond_to?(key) }
end

#check_snapshot_changedObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/glib/snapshot.rb', line 22

def check_snapshot_changed
  return true if changed?

  associations_for_snapshot.each do |association_name|
    if (association = self.class.reflect_on_association(association_name))
      case association.macro
      when :has_many
        public_send(association_name).each do |record|
          return true if record.changed?
        end
      when :has_one, :belongs_to
        return true if public_send(association_name).changed?
      end
    else
      raise "Invalid association: #{association_name}"
    end
  end

  false
end

#diff(snapshot = snapshot_prev) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/glib/snapshot.rb', line 127

def diff(snapshot = snapshot_prev)
  default_ignored_keys = ['updated_at', 'created_at']
  ignore_keys = default_ignored_keys

  if !watched_keys_for_snapshot.nil?
    ignored_keys_for_snapshot = attributes.except(*watched_keys_for_snapshot.map(&:to_s)).keys
    ignore_keys = (default_ignored_keys + ignored_keys_for_snapshot.map(&:to_s)).uniq
  end

  # always watch column with name *id
  ignore_keys.filter! { |key| !key.ends_with?('id') || key != 'id' }

  if snapshot.present?
    item, associations = snapshot.fetch_reified_items
  else
    item = OpenStruct.new(attributes: attributes_before_save || {})
    associations = {}
  end

  obj = {
    'item' => ::Hashdiff.diff(item.attributes.except(*ignore_keys), attributes.except(*ignore_keys))
  }

  obj['associations'] = associations_for_snapshot.reduce({}) do |prev, curr|
    first_record_off_same_collection = send(curr).first

    if !first_record_off_same_collection.respond_to?(:watched_keys_for_snapshot) && !first_record_off_same_collection.nil?
      raise NotImplementedError, "please add method 'watched_keys_for_snapshot' to #{first_record_off_same_collection.class}"
    end

    association_ignored_keys =
      if !first_record_off_same_collection.try(:watched_keys_for_snapshot).nil?
        assoc_ignore_keys = first_record_off_same_collection.attributes.except(*first_record_off_same_collection.watched_keys_for_snapshot.map(&:to_s)).keys.map(&:to_s)
        (default_ignored_keys + assoc_ignore_keys).uniq
      else
        default_ignored_keys
      end

    # always watch column with name *id
    association_ignored_keys.filter! { |key| !key.ends_with?('id') || key != 'id' }

    # attrs_before = (associations[curr] || []).map { |record| record.attributes.except(*association_ignored_keys) }
    # attrs_now = send(curr).order(id: :asc).map { |record| record.attributes.except(*association_ignored_keys) }

    before = (associations[curr] || [])
    now = send(curr).order(id: :asc)

    if before.blank?
      prev.merge(curr.to_s => ::Hashdiff.diff([], now.map { |record| record.attributes.except(*association_ignored_keys) }))
    else
      diff = before.map.with_index do |record_before, index|
        record_now = now.find_by(id: record_before.id)
        if record_now.blank?
          ['-', "[#{index}]", record_before.attributes.except(*association_ignored_keys)]
        elsif record_now.present?
          next if Hashdiff.diff(record_before.attributes.except(*association_ignored_keys), record_now.attributes.except(*association_ignored_keys)).blank?
          ['~', "[#{index}]", record_before.attributes.except(*association_ignored_keys), record_now.attributes.except(*association_ignored_keys)]
        end
      end.compact_blank

      diff2 = now.map.with_index do |record_now, index|
        record_before = before.detect { |record| record.id == record_now.id }
        if record_before.blank?
          ['+', "[#{index}]", record_now.attributes.except(*association_ignored_keys)]
        end
      end.compact_blank

      prev.merge(curr.to_s => (diff + diff2))
    end
  end

  obj
end

#glib_create_snapshot!(user, action) ⇒ Object

information need to be store:

  • action: create, update, destroy

  • track changes



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/glib/snapshot.rb', line 85

def glib_create_snapshot!(user, action)
  known_actions = ['create', 'update', 'destroy']

  raise 'unknown action' if !known_actions.include?(action.to_s)

  result = nil
  with_lock do
    version = last_version + 1
     = {
      action: action,
      diff: diff,
      version: version
    }
    snapshot_obj = {
      identifier: "#{self.class.to_s.underscore}_#{id}_version_#{version}",
      user: user,
      metadata: 
    }

    if user.is_a?(String)
      [:user] = user
      snapshot_obj.delete(:user)
    end

    # dont create version if same as before
    if !same_as_before?
      result = create_snapshot!(**snapshot_obj)
      remove_old_snapshot if result.present?
    end
  end
  result
end

#glib_revert_snapshot!(version) ⇒ Object



118
119
120
121
# File 'lib/glib/snapshot.rb', line 118

def glib_revert_snapshot!(version)
  snapshot = snapshots.find_by(identifier: "#{self.class.to_s.underscore}_#{id}_version_#{version}")
  snapshot.restore!
end

#interval_from_prev_versionObject



123
124
125
# File 'lib/glib/snapshot.rb', line 123

def interval_from_prev_version
  updated_at - snapshot_prev.created_at
end

#last_versionObject



215
216
217
218
219
# File 'lib/glib/snapshot.rb', line 215

def last_version
  return 0 if snapshot_prev.blank?

  snapshot_prev.['version']
end

#max_snapshotsObject



238
239
240
# File 'lib/glib/snapshot.rb', line 238

def max_snapshots
  10
end

#remove_old_snapshotObject



221
222
223
224
225
226
227
228
# File 'lib/glib/snapshot.rb', line 221

def remove_old_snapshot
  return if max_snapshots.nil?

  newest_ids = snapshots.order(id: :desc).limit(max_snapshots).ids
  return unless newest_ids.size >= max_snapshots

  snapshots.where.not(id: newest_ids).destroy_all
end

#same_as_before?Boolean

Returns:

  • (Boolean)


205
206
207
208
209
210
211
212
213
# File 'lib/glib/snapshot.rb', line 205

def same_as_before?
  return !snapshot_changed if snapshot_prev.blank?

  result = diff['item'].blank?

  result &&= diff['associations'].reduce(true) { |prev, (_k, v)| v.blank? && prev } if diff['associations'].present?

  result
end

#snapshot_prevObject



201
202
203
# File 'lib/glib/snapshot.rb', line 201

def snapshot_prev
  snapshots.order(id: :asc).last
end

#watched_keys_for_snapshotObject

Raises:

  • (NotImplementedError)


230
231
232
# File 'lib/glib/snapshot.rb', line 230

def watched_keys_for_snapshot
  raise NotImplementedError, "please add method 'watched_keys_for_snapshot' to #{self.class}"
end

#where_snapshots(user: nil, field: nil, action: nil, association: nil, association_action: nil, like: nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/glib/snapshot.rb', line 43

def where_snapshots(user: nil, field: nil, action: nil, association: nil, association_action: nil, like: nil)
  query = snapshots

  if user.present? && !user.is_a?(String)
    query = query.where(user_id: user.id, user_type: user.class.to_s)
  elsif user.present? && user.is_a?(String)
    query = query.where("metadata ->> 'user' = ?", user)
  end

  if field.present?
    query = query.where("metadata -> 'diff' ->> 'item' LIKE ?", "%#{field}%")
  end

  if action.present?
    query = query.where("metadata ->> 'action' = ?", action)
  end

  if association.present?
    query = query.where("metadata -> 'diff' -> 'associations' -> '#{association}' -> 0 IS NOT NULL")
  end

  if association_action.present?
    raise ArgumentError.new('association_action expect association to be present') if association.blank?

    known_actions = {
      'create' => '+',
      'destroy' => '-',
      'update' => '~'
    }
    query = query.where("metadata -> 'diff' -> 'associations' ->> '#{association}' LIKE ?", "%\"#{known_actions[association_action.to_s]}\"%")
  end

  if like.present?
    query = query.where("metadata ->> 'diff' LIKE ?", "%#{like}%")
  end

  query.to_a
end