module Audited::Auditor::ClassMethods

Public Instance Methods

audited(options = {}) click to toggle source

Configuration options

  • only - Only audit the given attributes

  • except - Excludes fields from being saved in the audit log. By default, Audited will audit all but these fields:

    [self.primary_key, inheritance_column, 'lock_version', 'created_at', 'updated_at']
    

    You can add to those by passing one or an array of fields to skip.

    class User < ActiveRecord::Base
      audited except: :password
    end
    
  • require_comment - Ensures that audit_comment is supplied before any create, update or destroy operation.

  • max_audits - Limits the number of stored audits.

  • if - Only audit the model when the given function returns true

  • unless - Only audit the model when the given function returns false

    class User < ActiveRecord::Base
      audited :if => :active?
    
      def active?
        self.status == 'active'
      end
    end
    
# File lib/audited/auditor.rb, line 49
def audited(options = {})
  # don't allow multiple calls
  return if included_modules.include?(Audited::Auditor::AuditedInstanceMethods)

  extend Audited::Auditor::AuditedClassMethods
  include Audited::Auditor::AuditedInstanceMethods

  class_attribute :audit_associated_with, instance_writer: false
  class_attribute :audited_options,       instance_writer: false
  attr_accessor :audit_version, :audit_comment

  self.audited_options = options
  normalize_audited_options

  self.audit_associated_with = audited_options[:associated_with]

  if audited_options[:comment_required]
    validate :presence_of_audit_comment
    before_destroy :require_comment if audited_options[:on].include?(:destroy)
  end

  has_many :audits, -> { order(version: :asc) }, as: :auditable, class_name: Audited.audit_class.name, inverse_of: :auditable
  Audited.audit_class.audited_class_names << to_s

  after_create :audit_create    if audited_options[:on].include?(:create)
  before_update :audit_update   if audited_options[:on].include?(:update)
  before_destroy :audit_destroy if audited_options[:on].include?(:destroy)

  # Define and set after_audit and around_audit callbacks. This might be useful if you want
  # to notify a party after the audit has been created or if you want to access the newly-created
  # audit.
  define_callbacks :audit
  set_callback :audit, :after, :after_audit, if: lambda { respond_to?(:after_audit, true) }
  set_callback :audit, :around, :around_audit, if: lambda { respond_to?(:around_audit, true) }

  enable_auditing
end
has_associated_audits() click to toggle source
# File lib/audited/auditor.rb, line 87
def has_associated_audits
  has_many :associated_audits, as: :associated, class_name: Audited.audit_class.name
end