Skip to content

Commit

Permalink
Merge pull request #402 from fatkodima/optimize-revisions
Browse files Browse the repository at this point in the history
Reduce db calls in #revisions method
  • Loading branch information
tbrisker committed Jan 15, 2018
2 parents 0c4730c + 91b17ac commit 70ad55c
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/audited/auditor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,15 @@ def without_auditing(&block)
# end
#
def revisions(from_version = 1)
audits = self.audits.from_version(from_version)
return [] if audits.empty?
audits.map(&:revision)
return [] if audits.from_version(from_version).empty?

loaded_audits = audits.select([:audited_changes, :version]).to_a
targeted_audits = loaded_audits.select { |audit| audit.version >= from_version }

targeted_audits.map do |audit|
ancestors = loaded_audits.select { |a| a.version <= audit.version }
revision_with(reconstruct_attributes(ancestors).merge(version: audit.version))
end
end

# Get a specific revision specified by the version number, or +:previous+
Expand Down Expand Up @@ -230,6 +236,12 @@ def auditing_enabled
def auditing_enabled=(val)
self.class.auditing_enabled = val
end

def reconstruct_attributes(audits)
attributes = {}
audits.each { |audit| attributes.merge!(audit.new_attributes) }
attributes
end
end # InstanceMethods

module AuditedClassMethods
Expand Down

0 comments on commit 70ad55c

Please sign in to comment.