Module: OpenTrace::AuditTracker

Defined in:
lib/opentrace/audit_tracker.rb

Overview

Auto-included concern on ActiveRecord::Base when audit_tracking is enabled. Captures before/after diffs on create, update, and destroy using saved_changes.

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
# File 'lib/opentrace/audit_tracker.rb', line 7

def self.included(base)
  base.after_create  { |record| OpenTrace::AuditTracker.track(record, :create) }
  base.after_update  { |record| OpenTrace::AuditTracker.track(record, :update) }
  base.after_destroy { |record| OpenTrace::AuditTracker.track(record, :destroy) }
end

.track(record, action) ⇒ Object



14
15
16
17
18
19
20
21
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
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
81
82
83
84
85
86
87
88
# File 'lib/opentrace/audit_tracker.rb', line 14

def track(record, action)
  buffer = Fiber[:opentrace_buffer]
  return unless buffer
  return unless OpenTrace.config.audit_tracking

  model_name = record.class.name
  return if excluded_model?(model_name)

  # Resolve actor
  actor_id = nil
  actor_type = nil
  actor_proc = OpenTrace.config.audit_actor
  if actor_proc.is_a?(Proc)
    actor = actor_proc.call rescue nil
    if actor
      actor_id = actor.respond_to?(:id) ? actor.id.to_s : actor.to_s
      actor_type = actor.class.name
    end
  end

  case action
  when :create
    after_values = filter_fields(record.attributes)
    buffer.record_audit(
      action: "create",
      record_type: model_name,
      record_id: record.id.to_s,
      actor_id: actor_id,
      actor_type: actor_type,
      changed_fields: nil,
      full_before: nil,
      full_after: after_values
    )

  when :update
    changes = record.saved_changes
    return if changes.empty?

    filtered = filter_changes(changes)
    return if filtered.empty?

    changed_fields = {}
    filtered.each do |field, (old_val, new_val)|
      changed_fields[field] = { "from" => old_val, "to" => new_val }
    end

    buffer.record_audit(
      action: "update",
      record_type: model_name,
      record_id: record.id.to_s,
      actor_id: actor_id,
      actor_type: actor_type,
      changed_fields: changed_fields,
      full_before: nil,
      full_after: nil
    )

  when :destroy
    before_values = filter_fields(record.attributes)
    buffer.record_audit(
      action: "destroy",
      record_type: model_name,
      record_id: record.id.to_s,
      actor_id: actor_id,
      actor_type: actor_type,
      changed_fields: nil,
      full_before: before_values,
      full_after: nil
    )
  end

  buffer.record_timeline(type: :audit, name: "#{model_name}##{action}")
rescue StandardError
  # Never affect the host app
end