Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 176 lines (138 sloc) 5.39 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
module PaperTrail

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


  module ClassMethods
    # Options:
    # :ignore an array of attributes for which a new +Version+ will not be created if only they change.
    # :meta a hash of extra data to store. You must add a column to the versions table for each key.
    # Values are objects or procs (which are called with +self+, i.e. the model with the paper
    # trail).
    def has_paper_trail(options = {})
      send :include, InstanceMethods

      cattr_accessor :ignore
      self.ignore = (options[:ignore] || []).map &:to_s

      cattr_accessor :meta
      self.meta = options[:meta] || {}
      
      cattr_accessor :paper_trail_active
      self.paper_trail_active = true

      has_many :versions, :as => :item, :order => 'created_at ASC, id ASC'

      after_create :record_create
      before_update :record_update
      after_destroy :record_destroy

      self.send(:define_method, "reified!") { @_reified = true }
      self.send(:define_method, "reified?") { !!@_reified }
    end

    def paper_trail_off
      self.paper_trail_active = false
    end

    def paper_trail_on
      self.paper_trail_active = true
    end
  end


  module InstanceMethods
    def record_create
      if self.class.paper_trail_active && PaperTrail.enabled?
        versions.create merge_metadata(:event => 'create', :whodunnit => PaperTrail.whodunnit)
      end
    end

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

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

    # Returns the object at the version that was valid at the given timestamp.
    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 ASC')
      version.reify if version
    end

    # Walk the versions to construct an audit trail of the edits made
    # over time, and by whom.
    def audit_trail(options={})
      # ignore updated_at by default because the version's created_at is good enough
      options[:attributes_to_ignore] = Array(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| options[:attributes_to_ignore].include?(k) }
        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

    protected

    # Override this method in your model to transform the whodunnit string
    # into something domain-specific. For example, to fetch a User instance by
    # its id.
    def transform_whodunnit(whodunnit)
      whodunnit
    end


    private

    def merge_metadata(data)
      meta.each do |k,v|
        data[k] = v.respond_to?(:call) ? v.call(self) : v
      end
      data
    end

    def previous_version
      previous = self.clone
      previous.id = id
      changes.each do |attr, ary|
        previous.send "#{attr}=", ary.first
      end
      previous
    end

    def object_to_string(object)
      object.attributes.to_yaml
    end

    def yaml_to_hash(yaml)
      return {} if yaml.nil?
      YAML::load(yaml).to_hash
    end

    # Returns an array of hashes, where each hash specifies the +:attribute+,
    # value +:before+ the change, and value +:after+ the change.
    def differences(before, after)
      before.diff(after).keys.sort.inject([]) do |diffs, k|
        diff = { :attribute => k, :before => before[k], :after => after[k] }
        diffs << diff; diffs
      end
    end

    # Returns all versions, newest first, including a pseudo-version that
    # represents the current version of the entity.
    def versions_including_current_in_descending_order
      v = self.versions.dup
      v << Version.new(:event => 'update',
        :object => object_to_string(self),
        :created_at => self.updated_at)
      v.reverse # newest first
    end
    
    def changed_and_we_care?
      changed? and !(changed - self.class.ignore).empty?
    end
  end

end

ActiveRecord::Base.send :include, PaperTrail
Something went wrong with that request. Please try again.