Class: Audit

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

Overview

Audit saves the changes to ActiveRecord models. It has the following attributes:

  • auditable: the ActiveRecord model that was changed

  • user: the user that performed the change; a string or an ActiveRecord model

  • action: one of create, update, or delete

  • audited_changes: a serialized hash of all the changes

  • comment: a comment set with the audit

  • created_at: Time that the change was performed

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.as_user(user, &block) ⇒ 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.



42
43
44
45
46
47
48
49
50
# File 'lib/acts_as_audited/audit.rb', line 42

def as_user(user, &block)
  Thread.current[:acts_as_audited_user] = user

  yieldval = yield

  Thread.current[:acts_as_audited_user] = nil

  yieldval
end

.audited_classesObject

Returns the list of classes that are being audited



35
36
37
# File 'lib/acts_as_audited/audit.rb', line 35

def audited_classes
  audited_class_names.map(&:constantize)
end

Instance Method Details

#ancestorsObject

Return all audits older than the current one.



107
108
109
110
# File 'lib/acts_as_audited/audit.rb', line 107

def ancestors
  self.class.where(['auditable_id = ? and auditable_type = ? and version <= ?',
    auditable_id, auditable_type, version])
end

#new_attributesObject

Returns a hash of the changed attributes with the new values



113
114
115
116
117
118
# File 'lib/acts_as_audited/audit.rb', line 113

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

#old_attributesObject

Returns a hash of the changed attributes with the old values



121
122
123
124
125
126
# File 'lib/acts_as_audited/audit.rb', line 121

def old_attributes
  (audited_changes || {}).inject({}.with_indifferent_access) do |attrs,(attr,values)|
    attrs[attr] = Array(values).first
    attrs
  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.



99
100
101
102
103
104
# File 'lib/acts_as_audited/audit.rb', line 99

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