From 3620c8c85e034dc770c0311f35e902e87a857fe8 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Thu, 24 Sep 2015 12:25:09 -0400 Subject: [PATCH] Move descriptions for rate limiting errors into the exception --- app/controllers/application_controller.rb | 12 +----------- lib/rate_limiter/limit_exceeded.rb | 14 +++++++++++++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index d9fe0a4976b..47f8836cb88 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -76,17 +76,7 @@ class ApplicationController < ActionController::Base # If they hit the rate limiter rescue_from RateLimiter::LimitExceeded do |e| - - time_left = "" - if e.available_in < 1.minute.to_i - time_left = I18n.t("rate_limiter.seconds", count: e.available_in) - elsif e.available_in < 1.hour.to_i - time_left = I18n.t("rate_limiter.minutes", count: (e.available_in / 1.minute.to_i)) - else - time_left = I18n.t("rate_limiter.hours", count: (e.available_in / 1.hour.to_i)) - end - - render_json_error I18n.t("rate_limiter.too_many_requests", time_left: time_left), type: :rate_limit, status: 429 + render_json_error e.description, type: :rate_limit, status: 429 end rescue_from PG::ReadOnlySqlTransaction do |e| diff --git a/lib/rate_limiter/limit_exceeded.rb b/lib/rate_limiter/limit_exceeded.rb index 2b85b467b07..c6685484897 100644 --- a/lib/rate_limiter/limit_exceeded.rb +++ b/lib/rate_limiter/limit_exceeded.rb @@ -2,10 +2,22 @@ class RateLimiter # A rate limit has been exceeded. class LimitExceeded < StandardError - attr_accessor :available_in + def initialize(available_in) @available_in = available_in end + + def description + time_left = "" + if @available_in < 1.minute.to_i + time_left = I18n.t("rate_limiter.seconds", count: @available_in) + elsif @available_in < 1.hour.to_i + time_left = I18n.t("rate_limiter.minutes", count: (@available_in / 1.minute.to_i)) + else + time_left = I18n.t("rate_limiter.hours", count: (@available_in / 1.hour.to_i)) + end + I18n.t("rate_limiter.too_many_requests", time_left: time_left) + end end end