class Rare::Throttler

Public Class Methods

new() click to toggle source
# File lib/rare/throttler.rb, line 5
def initialize
  @mutex = Mutex.new
end

Public Instance Methods

throttle(rpm:, key: 'default') { || ... } click to toggle source
# File lib/rare/throttler.rb, line 9
def throttle(rpm:, key: 'default')
  if rpm.to_f > 0
    sleep sleep_interval until allowed?(seconds(rpm), key)
  end

  yield if block_given?
end

Private Instance Methods

allowed?(seconds, key) click to toggle source
# File lib/rare/throttler.rb, line 23
def allowed?(seconds, key)
  @mutex.synchronize do
    now       = Time.now.to_f
    timestamp = get(key)

    if timestamp.nil? || timestamp < now - seconds
      set(key, now)
      return true
    end

    false
  end
end
get(key) click to toggle source
# File lib/rare/throttler.rb, line 37
def get(key)
  value = storage[key]

  return value.to_f if value && !value.is_a?(Float)

  value
end
seconds(rpm) click to toggle source
# File lib/rare/throttler.rb, line 19
def seconds(rpm)
  60.0 / rpm
end
set(key, value) click to toggle source
# File lib/rare/throttler.rb, line 45
def set(key, value)
  storage[key] = value
end
sleep_interval() click to toggle source
# File lib/rare/throttler.rb, line 53
def sleep_interval
  Rare.configuration.sleep_interval
end
storage() click to toggle source
# File lib/rare/throttler.rb, line 49
def storage
  Rare.configuration.storage
end