2013-03-21 16:48:14 -04:00
|
|
|
module PaperTrail
|
|
|
|
module Cleaner
|
2013-07-31 13:46:25 -04:00
|
|
|
# Destroys all but the most recent version(s) for items on a given date (or on all dates). Useful for deleting drafts.
|
|
|
|
#
|
|
|
|
# Options:
|
|
|
|
# :keeping An `integer` indicating the number of versions to be kept for each item per date.
|
|
|
|
# Defaults to `1`.
|
|
|
|
# :date Should either be a `Date` object specifying which date to destroy versions for or `:all`,
|
|
|
|
# which will specify that all dates should be cleaned. Defaults to `:all`.
|
|
|
|
# :item_id The `id` for the item to be cleaned on, or `nil`, which causes all items to be cleaned.
|
|
|
|
# Defaults to `nil`.
|
|
|
|
def clean_versions!(options = {})
|
|
|
|
options = {:keeping => 1, :date => :all}.merge(options)
|
|
|
|
gather_versions(options[:item_id], options[:date]).each do |item_id, versions|
|
2014-12-29 12:31:44 -05:00
|
|
|
versions.group_by { |v| v.send(PaperTrail.timestamp_field).to_date }.each do |date, _versions|
|
2014-03-18 15:56:53 -04:00
|
|
|
# remove the number of versions we wish to keep from the collection of versions prior to destruction
|
2014-12-29 12:31:44 -05:00
|
|
|
_versions.pop(options[:keeping])
|
|
|
|
_versions.map(&:destroy)
|
2013-03-21 16:48:14 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-07-30 17:58:44 -04:00
|
|
|
private
|
2013-07-16 20:53:18 -04:00
|
|
|
|
2013-07-31 13:46:25 -04:00
|
|
|
# Returns a hash of versions grouped by the `item_id` attribute formatted like this: {:item_id => PaperTrail::Version}.
|
|
|
|
# If `item_id` or `date` is set, versions will be narrowed to those pointing at items with those ids that were created on specified date.
|
|
|
|
def gather_versions(item_id = nil, date = :all)
|
2015-02-08 15:06:40 -05:00
|
|
|
raise ArgumentError.new("`date` argument must receive a Timestamp or `:all`") unless date == :all || date.respond_to?(:to_date)
|
2013-07-31 13:46:25 -04:00
|
|
|
versions = item_id ? PaperTrail::Version.where(:item_id => item_id) : PaperTrail::Version
|
2013-07-31 20:37:04 -04:00
|
|
|
versions = versions.between(date.to_date, date.to_date + 1.day) unless date == :all
|
|
|
|
versions = PaperTrail::Version.all if versions == PaperTrail::Version # if versions has not been converted to an ActiveRecord::Relation yet, do so now
|
2013-07-30 17:58:44 -04:00
|
|
|
versions.group_by(&:item_id)
|
2013-03-21 16:48:14 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|