2020-04-22 11:09:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Limitable
|
|
|
|
extend ActiveSupport::Concern
|
2020-05-27 14:08:14 -04:00
|
|
|
GLOBAL_SCOPE = :limitable_global_scope
|
2020-04-22 11:09:27 -04:00
|
|
|
|
|
|
|
included do
|
|
|
|
class_attribute :limit_scope
|
|
|
|
class_attribute :limit_name
|
|
|
|
self.limit_name = self.name.demodulize.tableize
|
|
|
|
|
|
|
|
validate :validate_plan_limit_not_exceeded, on: :create
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def validate_plan_limit_not_exceeded
|
2020-05-27 14:08:14 -04:00
|
|
|
if GLOBAL_SCOPE == limit_scope
|
|
|
|
validate_global_plan_limit_not_exceeded
|
|
|
|
else
|
|
|
|
validate_scoped_plan_limit_not_exceeded
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_scoped_plan_limit_not_exceeded
|
2020-04-22 11:09:27 -04:00
|
|
|
scope_relation = self.public_send(limit_scope) # rubocop:disable GitlabSecurity/PublicSend
|
|
|
|
return unless scope_relation
|
|
|
|
|
|
|
|
relation = self.class.where(limit_scope => scope_relation)
|
2020-05-27 14:08:14 -04:00
|
|
|
limits = scope_relation.actual_limits
|
2020-04-22 11:09:27 -04:00
|
|
|
|
2020-05-27 14:08:14 -04:00
|
|
|
check_plan_limit_not_exceeded(limits, relation)
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_global_plan_limit_not_exceeded
|
|
|
|
relation = self.class.all
|
|
|
|
limits = Plan.default.actual_limits
|
|
|
|
|
|
|
|
check_plan_limit_not_exceeded(limits, relation)
|
|
|
|
end
|
|
|
|
|
|
|
|
def check_plan_limit_not_exceeded(limits, relation)
|
|
|
|
return unless limits.exceeded?(limit_name, relation)
|
|
|
|
|
|
|
|
errors.add(:base, _("Maximum number of %{name} (%{count}) exceeded") %
|
|
|
|
{ name: limit_name.humanize(capitalize: false), count: limits.public_send(limit_name) }) # rubocop:disable GitlabSecurity/PublicSend
|
2020-04-22 11:09:27 -04:00
|
|
|
end
|
|
|
|
end
|