Module: PaperTrailAudit::Model

Included in:
ActiveRecord::Base
Defined in:
lib/paper_trail-audit.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
# File 'lib/paper_trail-audit.rb', line 6

def self.included(base)
  base.send :extend, ClassMethods
end

Instance Method Details

#calculate_audit_for(param) ⇒ array of Change objects

Returns the audit list for the specified column

Parameters:

  • param: (symbol)

    symbol to query

Returns:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/paper_trail-audit.rb', line 14

def calculate_audit_for(param)
  #Gets all flattened attribute lists
  #objects are a hash of
  #{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}
  objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},
    self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten
  #rejecting objects with no update time, orders by the updated at times in ascending order
  objects = objects.select {|e| e[:attributes]["updated_at"]}.sort_by {|e| e[:attributes]["updated_at"]}
  result = []
  #Add the initial state if the first element has a value
  if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)
    result <<  PaperTrailAudit::Change.new({old_value: nil,
        new_value: objects.first[:attributes][param.to_s],
        time: objects.first[:attributes]["updated_at"],
        whodunnit: objects.first[:whodunnit]
        })
  end
  objects.each_cons(2) do |a,b|
    if a[:attributes][param.to_s] != b[:attributes][param.to_s]
      result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],
        new_value: b[:attributes][param.to_s],
        time: b[:attributes]["updated_at"],
        whodunnit: b[:whodunnit]
      })
    end
  end
  result
end