Search code examples
ruby-on-railspaper-trail-gem

Set version limit per model in Papertrail?


Is there a way to limit the number of versions, per model, in Papertrail?

E.g., I know I can set a global limit with

PaperTrail.config.version_limit = 3

But I don't see a way to set that per model, with something like

class Article < ActiveRecord::Base
  has_paper_trail :limit => [10]
end

I also don't want to just limit the number of versions saved (to say ten) but have it so only the latest ten are saved (same as with the config version setting).


Solution

  • Here is the answer you want:

    Add constant "PAPER_TRAIL_VERSION_LIMIT" to your Article model like below

    # models/article.rb
    class Article < ActiveRecord::Base
      has_paper_trail
      # 10 mean you article will have 11 version include 'create' version
      PAPER_TRAIL_VERSION_LIMIT = 10
    end
    

    Add below codes to the bottom of PaperTrail config file

    # /config/initializers/paper_trail.rb
    module PaperTrail
      class Version < ActiveRecord::Base
        private
        def enforce_version_limit!
          limit = PaperTrail.config.version_limit
          # This is the key custom line
          limit = item.class::PAPER_TRAIL_VERSION_LIMIT  if item.class.const_defined?("PAPER_TRAIL_VERSION_LIMIT")
          return unless limit.is_a? Numeric
          previous_versions = sibling_versions.not_creates
          return unless previous_versions.size > limit
          excess_versions = previous_versions - previous_versions.last(limit)
          excess_versions.map(&:destroy)
        end
      end
    end
    

    Enjoy it ! :D