Module: HasAuditTrail::AuditTrailInclude::InstanceMethods

Defined in:
lib/has_audit_trail/audit_trail_include.rb

Instance Method Summary collapse

Instance Method Details

#_audit_createObject



56
57
58
59
60
# File 'lib/has_audit_trail/audit_trail_include.rb', line 56

def _audit_create
  self.audited_columns.each do |field|
    _write_audit(:action => :create, :new_value => self.send(field.to_sym).to_yaml, :property => field.to_sym)
  end
end

#_audit_destroyObject



62
63
64
# File 'lib/has_audit_trail/audit_trail_include.rb', line 62

def _audit_destroy
  _write_audit(:action => :destroy)
end

#_audit_updateObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/has_audit_trail/audit_trail_include.rb', line 66

def _audit_update
  if changed?
    changes.each do |field, change|
      if self.audited_columns.include? field.to_sym
        _write_audit(:action => :update, :old_value => change[0].to_yaml, :new_value => change[1].to_yaml, :property => field)
      end
    end
  end

  # direct associations
  audited_collections.try(:each) do |attr|
    unless new_record?
      if changed_collections[attr][:added].size > 0
        old = self.send(attr) - changed_collections[attr][:added]

        _write_audit(:action => :update, :old_value => old.collect { |x| x.name }, :new_value => self.send(attr).collect {|x|x.name}, :property => attr)
        changed_collections[attr][:added] = []
      end
      if changed_collections[attr][:removed].size > 0
        old = self.send(attr) + changed_collections[attr][:removed]

        _write_audit(:action => :update, :old_value => old.collect { |x| x.name }, :new_value => self.send(attr).collect {|x|x.name}, :property => attr)
        changed_collections[attr][:removed] = []
      end
    end
  end

  # accepts_nested_attributes_for
  audited_associations.try(:each) do |attr, procs|
    unless new_record?
      self.send(attr).each do |c|
        if c.changed?
          c.changes.each do |field, change|
            if change[0].to_s != change[1].to_s
              _write_audit(:action => :update, :old_value => change[0].to_yaml, :new_value => change[1].to_yaml, :property => procs[:label].call(c))
            end
          end
        end
      end
    end
  end
end

#_write_audit(attrs) ⇒ Object



51
52
53
54
# File 'lib/has_audit_trail/audit_trail_include.rb', line 51

def _write_audit(attrs)
  attrs.merge!(:object => self.class.model_name, :object_id => self.id)
  AuditTrail.create!(attrs)
end