class Allowed::Throttle
Attributes
limit[R]
options[R]
Public Class Methods
new(limit, options = {})
click to toggle source
# File lib/allowed/throttle.rb, line 5 def initialize(limit, options = {}) @limit = limit @options = options end
Public Instance Methods
callback()
click to toggle source
# File lib/allowed/throttle.rb, line 10 def callback options.fetch(:callback, -> (record) { }) end
message()
click to toggle source
# File lib/allowed/throttle.rb, line 14 def message options.fetch(:message, "Limit reached.") end
valid?(record)
click to toggle source
# File lib/allowed/throttle.rb, line 18 def valid?(record) return true if skip?(record) scope_for(record).count < allowed_count(record) end
Private Instance Methods
allowed_count(record)
click to toggle source
# File lib/allowed/throttle.rb, line 48 def allowed_count(record) case limit when Integer limit when Symbol record.__send__(limit) end end
scope_for(record)
click to toggle source
# File lib/allowed/throttle.rb, line 26 def scope_for(record) scope = record.class.where("created_at >= ?", timeframe) attributes = Array(options.fetch(:scope, [])) attributes.inject(scope) do |scope, attribute| scope.where(attribute => record.__send__(attribute)) end end
skip?(record)
click to toggle source
# File lib/allowed/throttle.rb, line 34 def skip?(record) return unless method = options[:unless] if method.is_a?(Symbol) method = record.method(method).call else method.call(record) end end
timeframe()
click to toggle source
# File lib/allowed/throttle.rb, line 44 def timeframe options.fetch(:per, 1.day).ago end