Module: Glib::Snapshot

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

Instance Method Summary collapse

Instance Method Details

#associations_for_snapshotObject



245
246
247
# File 'lib/glib/snapshot.rb', line 245

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
42
43
44
45
46
47
48
49
# File 'lib/glib/snapshot.rb', line 22

def check_snapshot_changed
  return true if changed?

  associations_for_snapshot.each do |association_name|
    association = self.class.reflect_on_association(association_name)
    association_value = public_send(association_name)

    if active_storage_association?(association, association_value)
      active_storage_records(association_value).each do |record|
        return true if record.changed?
      end
      next
    end

    raise "Invalid association: #{association_name}" if association.nil?

    case association.macro
    when :has_many
      association_value.each do |record|
        return true if record.changed?
      end
    when :has_one, :belongs_to
      return true if association_value&.changed?
    end
  end

  false
end

#diff(snapshot = snapshot_prev) ⇒ Object



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
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/glib/snapshot.rb', line 135

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.reject! { |key| key == 'id' || key.ends_with?('_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| # rubocop:disable Glib/MultilineMethodCallStyle
    association_records = records_for_snapshot(curr)
    first_record_off_same_collection = association_records.first

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

    association_ignored_keys =
      if active_storage_record?(first_record_off_same_collection)
        default_ignored_keys
      elsif !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.reject! { |key| key == 'id' || key.ends_with?('_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 = association_records

    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



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/glib/snapshot.rb', line 93

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



126
127
128
129
# File 'lib/glib/snapshot.rb', line 126

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



131
132
133
# File 'lib/glib/snapshot.rb', line 131

def interval_from_prev_version
  updated_at - snapshot_prev.created_at
end

#last_versionObject



226
227
228
229
230
# File 'lib/glib/snapshot.rb', line 226

def last_version
  return 0 if snapshot_prev.blank?

  snapshot_prev.['version']
end

#max_snapshotsObject



249
250
251
# File 'lib/glib/snapshot.rb', line 249

def max_snapshots
  10
end

#remove_old_snapshotObject



232
233
234
235
236
237
238
239
# File 'lib/glib/snapshot.rb', line 232

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



216
217
218
219
220
221
222
223
224
# File 'lib/glib/snapshot.rb', line 216

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



212
213
214
# File 'lib/glib/snapshot.rb', line 212

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

#watched_keys_for_snapshotObject

Raises:

  • (NotImplementedError)


241
242
243
# File 'lib/glib/snapshot.rb', line 241

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



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
81
82
83
84
85
86
87
88
# File 'lib/glib/snapshot.rb', line 51

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