Module: PaperTrail::InstanceMethods

Defined in:
lib/paper_trail/has_paper_trail.rb

Instance Method Summary collapse

Instance Method Details

#audit_trail(options = {}) ⇒ Object

Walk the versions to construct an audit trail of the edits made over time, and by whom.



65
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
# File 'lib/paper_trail/has_paper_trail.rb', line 65

def audit_trail options={}
  options[:attributes_to_ignore] ||= %w(updated_at)

  audit_trail = []

  versions_desc = versions_including_current_in_descending_order

  versions_desc.each_with_index do |version, index|
    previous_version = versions_desc[index + 1]
    break if previous_version.nil?

    attributes_after = yaml_to_hash(version.object)
    attributes_before = yaml_to_hash(previous_version.object)

    # remove some attributes that we don't need to report
    [attributes_before, attributes_after].each do |hash| 
      hash.reject! { |k,v| k.in? Array(options[:attributes_to_ignore]) }
    end

    audit_trail << { 
      :event => previous_version.event,
      :changed_by => transform_whodunnit(previous_version.whodunnit),
      :changed_at => previous_version.created_at,
      :changes => differences(attributes_before, attributes_after)
      }
  end

  audit_trail
end

#record_createObject



33
34
35
36
# File 'lib/paper_trail/has_paper_trail.rb', line 33

def record_create
  versions.create(:event     => 'create',
                  :whodunnit => PaperTrail.whodunnit) if self.class.paper_trail_active
end

#record_destroyObject



46
47
48
49
50
# File 'lib/paper_trail/has_paper_trail.rb', line 46

def record_destroy
  versions.create(:event     => 'destroy',
                  :object    => object_to_string(previous_version),
                  :whodunnit => PaperTrail.whodunnit) if self.class.paper_trail_active
end

#record_updateObject



38
39
40
41
42
43
44
# File 'lib/paper_trail/has_paper_trail.rb', line 38

def record_update
  if changed? and self.class.paper_trail_active
    versions.build :event     => 'update',
                   :object    => object_to_string(previous_version),
                   :whodunnit => PaperTrail.whodunnit
  end
end

#version_at(timestamp) ⇒ Object

Returns the object at the version that was valid at the given timestamp.



53
54
55
56
57
58
59
60
61
# File 'lib/paper_trail/has_paper_trail.rb', line 53

def version_at timestamp
  # short-circuit if the current state is valid
  return self if self.updated_at < timestamp
  
  version = versions.first(
    :conditions => ['created_at < ?', timestamp], 
    :order => 'created_at DESC')
  version.reify if version
end