Class: RailsAuditLog::AuditLogEntry

Inherits:
ApplicationRecord show all
Defined in:
app/models/rails_audit_log/audit_log_entry.rb

Constant Summary collapse

EVENTS =
%w[create update destroy].freeze
BLOB_COLUMNS =
%w[object_changes object metadata].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configure_connection!Object



8
9
10
11
12
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 8

def self.configure_connection!
  return unless (opts = RailsAuditLog.connects_to)

  connects_to(**opts)
end

Instance Method Details

#changed_attributesObject



91
92
93
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 91

def changed_attributes
  object_changes&.keys || []
end

#diffObject



95
96
97
98
99
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 95

def diff
  return {} unless object_changes

  object_changes.transform_values { |from_to| { from: from_to[0], to: from_to[1] } }
end

#nextObject



87
88
89
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 87

def next
  self.class.where(item_type: item_type, item_id: item_id).where("id > ?", id).order(id: :asc).first
end

#previousObject



83
84
85
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 83

def previous
  self.class.where(item_type: item_type, item_id: item_id).where("id < ?", id).order(id: :desc).first
end

#reifyObject

Instance methods



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
# File 'app/models/rails_audit_log/audit_log_entry.rb', line 52

def reify
  return nil if event == "create"

  klass = item_type.constantize

  if object.present?
    instance = klass.new
    instance.assign_attributes(object.except("id"))
    instance.id = object.fetch("id") { item_id }
    return instance
  end

  # Fallback: diff-only mode or entries recorded before snapshot support.
  # Filter to column names so association-change entries (e.g. tags, comments)
  # don't get assigned to the record as if they were scalar attributes.
  column_names = klass.column_names.map(&:to_s)
  from_attrs = (object_changes || {})
    .select { |k, _| column_names.include?(k) }
    .transform_values { |from_to| from_to[0] }

  if event == "update"
    record = klass.find_by(id: item_id)
    from_attrs = record.attributes.merge(from_attrs) if record
  end

  instance = klass.new
  instance.assign_attributes(from_attrs.except("id"))
  instance.id = from_attrs.fetch("id") { item_id }
  instance
end