Sha256: 634644512b29c7cb79c6bdd2c164740e80dfe85874e767c7bf2b79fd02bc6058

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

module PaperTrailScrapbook
  # Class UserJournal provides history for a user, optionally scoped by
  # object class and/or date range
  #
  # @author Jason Dinsmore <jason@dinjas.com>
  #
  class UserJournal
    include Adamantium::Flat

    def initialize(user, opts = {})
      @user     = user
      @user_id  = String(user.id)
      @options  = opts
      @starts   = options[:start] || Time.at(0).in_time_zone
      @ends     = options[:end] || Time.current.in_time_zone

      @versions = PaperTrail::Version.where(query_params)
    end

    # Retries textual historical analysis of versions
    #
    # @return [String] analyzed versions
    #
    def story
      s = versions.map do |v|
        JournalEntry.new(v).story
      end.compact

      s.reverse! if PaperTrailScrapbook.config.recent_first

      s.join("\n\n")

      "#{preface}#{s.presence || 'No history'}"
    end

    private

    def preface
      "Between #{when_range}, #{user} made the following #{what} changes:\n\n"
        .squeeze(' ')
    end

    def query_params
      params = { whodunnit: user_id }
      return params if options.empty?

      params.merge(item_type:  what,
                   created_at: starts..ends)
            .delete_if { |_, v| v.presence.nil? }
    end

    def time_format
      PaperTrailScrapbook.config.time_format
    end

    def what
      String(options.fetch(:klass, nil)).presence
    end

    def when_range
      "#{starts.strftime(time_format)} and #{ends.strftime(time_format)}"
    end

    attr_reader :user, :user_id, :versions, :options, :starts, :ends
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
paper_trail_scrapbook-0.1.17 lib/paper_trail_scrapbook/user_journal.rb
paper_trail_scrapbook-0.1.16 lib/paper_trail_scrapbook/user_journal.rb
paper_trail_scrapbook-0.1.15 lib/paper_trail_scrapbook/user_journal.rb