Class: PlanLimits

Inherits:
ApplicationRecord show all
Defined in:
app/models/plan_limits.rb

Constant Summary collapse

LimitUndefinedError =
Class.new(StandardError)

Instance Method Summary collapse

Methods inherited from ApplicationRecord

at_most, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, underscore, without_order

Instance Method Details

#exceeded?(limit_name, subject, alternate_limit: 0) ⇒ Boolean

Returns:

  • (Boolean)

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/models/plan_limits.rb', line 8

def exceeded?(limit_name, subject, alternate_limit: 0)
  limit = limit_for(limit_name, alternate_limit: alternate_limit)
  return false unless limit

  case subject
  when Integer
    subject >= limit
  when ActiveRecord::Relation
    # We intentionally not accept just plain ApplicationRecord classes to
    # enforce the subject to be scoped down to a relation first.
    #
    # subject.count >= limit value is slower than checking
    # if a record exists at the limit value - 1 position.
    subject.offset(limit - 1).exists?
  else
    raise ArgumentError, "#{subject.class} is not supported as a limit value"
  end
end

#limit_for(limit_name, alternate_limit: 0) ⇒ Object


27
28
29
30
31
32
33
34
35
# File 'app/models/plan_limits.rb', line 27

def limit_for(limit_name, alternate_limit: 0)
  limit = read_attribute(limit_name)
  raise LimitUndefinedError, "The limit `#{limit_name}` is undefined" if limit.nil?

  alternate_limit = alternate_limit.call if alternate_limit.respond_to?(:call)

  limits = [limit, alternate_limit]
  limits.map(&:to_i).select(&:positive?).min
end