module Raterr::Mixin

Attributes

options[R]
request[R]

Public Class Methods

new(request, options) click to toggle source
# File lib/raterr/mixin.rb, line 6
def initialize(request, options)
  @request = request
  @options = options
end

Public Instance Methods

allowed?() click to toggle source
# File lib/raterr/mixin.rb, line 18
def allowed?
  reset_cache if Time.now > rate_period
  fetch_cache['attempts'] <= max_per_period
end
proceed() click to toggle source
# File lib/raterr/mixin.rb, line 23
def proceed
  attempts = fetch_cache['attempts'] + 1
  set_cache(attempts)

  {
    status: 200,
    attempts: attempts
  }
end
rate_limit_exceeded() click to toggle source
# File lib/raterr/mixin.rb, line 11
def rate_limit_exceeded
  {
    status: options[:code] || Raterr::DEFAULTS[:code],
    text: Raterr::DEFAULTS[:message] % { time: try_after }
  }
end

Private Instance Methods

container() click to toggle source
# File lib/raterr/mixin.rb, line 57
def container
  @container ||= StoreContainer.new(store: Raterr.store, identifier: identifier)
end
fetch_cache() click to toggle source
# File lib/raterr/mixin.rb, line 40
def fetch_cache
  container.resolve(:get)
end
identifier() click to toggle source
# File lib/raterr/mixin.rb, line 35
def identifier
  # TODO: extend with other options from the request
  request.ip.to_s
end
reset_cache() click to toggle source
# File lib/raterr/mixin.rb, line 53
def reset_cache
  container.resolve(:delete, identifier)
end
set_cache(value) click to toggle source
# File lib/raterr/mixin.rb, line 44
def set_cache(value)
  cache_attributes = {}.tap do |cache|
    cache['attempts'] = value
    cache['start_time'] = start_time
  end

  container.resolve(:set, cache_attributes)
end
start_time() click to toggle source
# File lib/raterr/mixin.rb, line 61
def start_time
  start_time = fetch_cache['start_time']
  # Depending on the storage option start_time can be
  # either a Time object or a string
  return Time.parse(start_time) if start_time.is_a?(String)
  start_time
end