Class: Version

Inherits:
PaperTrail::Version
  • Object
show all
Defined in:
app/models/polymorphic/version.rb

Constant Summary collapse

ASSETS =
%w[all tasks campaigns leads accounts contacts opportunities comments emails]
EVENTS =
%w[all_events create view update destroy]
DURATION =
%w[one_hour one_day two_days one_week two_weeks one_month]

Class Method Summary collapse

Class Method Details

.history(object) ⇒ Object



60
61
62
# File 'app/models/polymorphic/version.rb', line 60

def history(object)
  related_to(object).exclude_events(:view).default_order
end

.latest(options = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'app/models/polymorphic/version.rb', line 45

def latest(options = {})
  includes(:item, :related, :user)
    .where(({ item_type: options[:asset] } if options[:asset]))
    .where(({ event:     options[:event] } if options[:event]))
    .where(({ whodunnit: options[:user].to_s } if options[:user]))
    .where('versions.created_at >= ?', Time.zone.now - (options[:duration] || 2.days))
    .limit(options[:max])
    .default_order
end

.recent_for_user(user, limit = 10) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/models/polymorphic/version.rb', line 24

def recent_for_user(user, limit = 10)
  # Hybrid SQL/Ruby to build a unique list of the most recent entities that the
  # user has interacted with
  versions = []
  offset = 0
  while versions.size < limit
    query = includes(:item)
            .where(whodunnit: user.id.to_s)
            .where(item_type: ENTITIES)
            .limit(limit * 2)
            .offset(offset)
            .default_order

    break if query.empty?
    versions += query.select { |v| v.item.present? }
    versions.uniq! { |v| [v.item_id, v.item_type] }
    offset += limit * 2
  end
  versions[0...10]
end


55
56
57
58
# File 'app/models/polymorphic/version.rb', line 55

def related_to(object)
  where('(item_id = :id AND item_type = :type) OR (related_id = :id AND related_type = :type)',
        id: object.id, type: object.class.name)
end

.visible_to(user) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'app/models/polymorphic/version.rb', line 64

def visible_to(user)
  all.to_a.delete_if do |version|
    if item = version.item || version.reify
      if item.respond_to?(:access) # NOTE: Tasks don't have :access as of yet.
        # Delete from scope if it shouldn't be visible
        next item.user_id != user.id &&
          item.assigned_to != user.id &&
          (item.access == "Private" ||
            (item.access == "Shared" &&
             !item.permissions.map(&:user_id).include?(user.id)))
      end
      # Don't delete any objects that don't have :access method (e.g. tasks)
      next false
    end
    # Delete from scope if no object can be found or reified (e.g. from 'show' events)
    true
  end
end