module PaperTrailAudit::Model::ClassMethods

Public Instance Methods

paper_trail_audit_for(*params) click to toggle source

Defines the functions which perform the audit generation

Note: instead of looking at the type and performing a transformation we could simply reify the versions and make the function calls, however this causes a pretty significant performance hit, on an object with 100 versions the reify version was about 4x slower, although with low version counts the slowdown was much smaller, something like 1.06

@param [array of params to audit] *params describe *params

# File lib/paper_trail-audit.rb, line 53
def paper_trail_audit_for(*params)
  #return warn("PaperTrailAudit WARNING: No table exists for #{self}") if self.connection.tables.empty?
  params = params.flatten
  params.each do |param|
    reflection = self.reflect_on_all_associations(:belongs_to).select{|e| e.name == param}.first
    if(reflection)
      define_method param.to_s+"_changes" do
        self.calculate_audit_for(reflection.foreign_key).each do |o|
          o.old_value = reflection.klass.find(o.old_value) if o.old_value
          o.new_value = reflection.klass.find(o.new_value) if o.new_value
        end
      end
      next
    end

    if self.defined_enums.include?(param.to_s)
      #if it's an enum, wrap the values to the enum keys
      define_method param.to_s+"_changes" do
        self.calculate_audit_for(param).each do |o|
          o.old_value = self.defined_enums[param.to_s].key(o.old_value)
          o.new_value = self.defined_enums[param.to_s].key(o.new_value)
        end
      end
    else
      #Define a method which returns a list of audit change events
      define_method param.to_s+"_changes" do
        self.calculate_audit_for(param)
      end
    end
  end
end