Sha256: 29dc7c6f4fa0c1c2bd8ea107bcc1ae564e4b279a7966caddc3adaec656e9fceb

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

# coding: utf-8
module ActsAsFootprintable
  module Footprinter
    def self.included(base)
      base.class_eval do
        has_many :footprints, :class_name => 'ActsAsFootprintable::Footprint', :as => :footprinter, :dependent => :destroy do
          def footprintable
            includes(:footprintable).map(&:footprintable)
          end
        end
      end
    end

    def leave_footprints(footprintable)
      footprint = ActsAsFootprintable::Footprint.new(:footprintable => footprintable, :footprinter => self)
      if footprint.save
        true
      else
        false
      end
    end

    def access_histories_for(klass, limit=nil)
      get_access_history_records(footprints.for_type(klass), limit)
    end

    def access_histories(limit=nil)
      get_access_history_records(footprints, limit)
    end

    private
    def get_access_history_records(target, limit=nil)
      footprints.where(:id => recent_footprint_ids(target, limit))
    end

    def table_name
      ActsAsFootprintable::Footprint.table_name
    end

    def recent_footprint_ids(target, limit=nil)
      recent_footprints = target.group("#{table_name}.footprintable_id, #{table_name}.footprintable_type").
          select("#{table_name}.footprintable_id, #{table_name}.footprintable_type, MAX(#{table_name}.created_at)")
      records = footprints.where("(#{table_name}.footprintable_id, #{table_name}.footprintable_type, #{table_name}.created_at) IN (#{recent_footprints.arel.to_sql})")
      records = records.order("footprints.created_at desc")
      records = records.limit(limit) unless limit.nil?
      records.pluck(:id)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_footprintable-0.2.2 lib/acts_as_footprintable/footprinter.rb