Created
February 5, 2021 15:33
-
-
Save trobrock/52dc4b31880b7365d67f066b084e7188 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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