docbrown/app/lib/throttled_call.rb
Michael Kohl a432ab7b3f
Spike: Add ThrottledCall utility class (#12779)
* Add ThrottledCall utility class

* Rename class level interface method

* Update worker to use ThrottledCall

* Add ThrottledCall spec to worker
2021-03-01 08:51:04 +07:00

16 lines
531 B
Ruby

class ThrottledCall
KEY_TEMPLATE = "throttled_call.%<key>s".freeze
# Executes the provided block and then blocks its execution for the provided
# time interval
#
# @param key [String, Symbol] used for generating the Redis cache key
# @param throttle_for [ActiveSupport::Duration] blocking time interval
def self.perform(key, throttle_for:)
namespaced_key = format(KEY_TEMPLATE, key: key)
Rails.cache.fetch(namespaced_key, expires_in: throttle_for) do
yield if block_given?
true
end
end
end