module Mongoid::SimpleAudit::Model::ClassMethods

Public Instance Methods

simple_audit(options = {}, &block) click to toggle source

Configuration options

  • username_method => symbol - Call this method on the current user to get the name

With no block, all the attributes and belongs_to associations (id and to_s) of the audited model will be logged.

class Booking
  # this is equivalent to passing no block
  simple_audit do |audited_record|
    audited_record.attributes
  end
end

If a block is given, the data returned by the block will be saved in the audit’s change log.

class Booking
  has_many :housing_units
  simple_audit do |audited_record|
    {
      :some_relevant_attribute => audited_record.some_relevant_attribute,
      :human_readable_serialization_of_aggregated_models => audited_record.housing_units.collect(&:to_s),
      ...
    }
  end
end
# File lib/mongoid/simple_audit/simple_audit.rb, line 50
def simple_audit(options = {}, &block)
  class_eval do

    class_attribute :username_method
    class_attribute :audit_changes
    class_attribute :audit_changes_only

    self.username_method = (options[:username_method] || :name).to_sym
    self.audit_changes_only = options[:audit_changes_only] === true

    attributes_and_associations = proc do |record|
      changes = record.attributes
      as_types = [:belongs_to]
      as_types << :embeds_one if record.singleton_class.included_modules.include? Mongoid::Document

      as_types.each do |as_type|
        record.class.reflect_on_all_associations( as_type ).each do |assoc|
          changes[assoc.name] = record.send(assoc.name).to_s
        end
      end
      changes
    end
    audit_changes_proc = block_given? ? block.to_proc : attributes_and_associations
    
    self.audit_changes = audit_changes_proc
    after_create {|record| record.class.audit(record, :create, nil)}
    after_update {|record| record.class.audit(record, :update, nil)}
  end
end