Class: Audited::Audit

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/audited/audit.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.as_user(user) ⇒ Object

All audits made during the block called will be recorded as made by user. This method is hopefully threadsafe, making it ideal for background operations that require audit information.


134
135
136
137
138
139
140
# File 'lib/audited/audit.rb', line 134

def self.as_user(user)
  last_audited_user = ::Audited.store[:audited_user]
  ::Audited.store[:audited_user] = user
  yield
ensure
  ::Audited.store[:audited_user] = last_audited_user
end

.audited_classesObject

Returns the list of classes that are being audited


127
128
129
# File 'lib/audited/audit.rb', line 127

def self.audited_classes
  audited_class_names.map(&:constantize)
end

.collection_cache_key(collection = all) ⇒ Object

use created_at as timestamp cache key


165
166
167
# File 'lib/audited/audit.rb', line 165

def self.collection_cache_key(collection = all, *)
  super(collection, :created_at)
end

Instance Method Details

#ancestorsObject

Return all audits older than the current one.


63
64
65
# File 'lib/audited/audit.rb', line 63

def ancestors
  self.class.ascending.auditable_finder(auditable_id, auditable_type).to_version(version)
end

#new_attributesObject

Returns a hash of the changed attributes with the new values


77
78
79
80
81
# File 'lib/audited/audit.rb', line 77

def new_attributes
  (audited_changes || {}).each_with_object({}.with_indifferent_access) do |(attr, values), attrs|
    attrs[attr] = values.is_a?(Array) ? values.last : values
  end
end

#old_attributesObject

Returns a hash of the changed attributes with the old values


84
85
86
87
88
# File 'lib/audited/audit.rb', line 84

def old_attributes
  (audited_changes || {}).each_with_object({}.with_indifferent_access) do |(attr, values), attrs|
    attrs[attr] = Array(values).first
  end
end

#revisionObject

Return an instance of what the object looked like at this revision. If the object has been destroyed, this will be a new record.


69
70
71
72
73
74
# File 'lib/audited/audit.rb', line 69

def revision
  clazz = auditable_type.constantize
  (clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
    self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
  end
end

#undoObject

Allows user to undo changes


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/audited/audit.rb', line 91

def undo
  case action
  when "create"
    # destroys a newly created record
    auditable.destroy!
  when "destroy"
    # creates a new record with the destroyed record attributes
    auditable_type.constantize.create!(audited_changes)
  when "update"
    # changes back attributes
    auditable.update!(audited_changes.transform_values(&:first))
  else
    raise StandardError, "invalid action given #{action}"
  end
end