Skip to content

Instantly share code, notes, and snippets.

@trobrock
Created February 5, 2021 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trobrock/52dc4b31880b7365d67f066b084e7188 to your computer and use it in GitHub Desktop.
Save trobrock/52dc4b31880b7365d67f066b084e7188 to your computer and use it in GitHub Desktop.
module RateLimitable
extend ActiveSupport::Concern
class_methods do
def rate_limiter(name, key:, threshold:, interval:, retry_from: [])
limiter_name = "#{name}_limiter"
define_method(limiter_name) do |&block|
limiter = instance_variable_get("@#{limiter_name}".to_sym)
limiter ||= instance_variable_set("@#{limiter_name}".to_sym, Ratelimit.new(name))
limiter.exec_within_threshold(__send__(key), threshold: threshold, interval: interval) do
result = Retryable.retryable(tries: 3, on: retry_from) { block.call }
limiter.add __send__(key)
result
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment