Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution for throttle puzzles
class GetShots
def initialize(rate_limit, time_window)
@rate_limit = rate_limit
@time_window = time_window
@calls_count = 0
end
def get_shot(type, params)
@calls_count += 1
@invoked_at ||= Time.now
send("#{type}_shot", params)
if @calls_count >= @rate_limit
# WAIT
time_left = (@invoked_at + @time_window) - Time.now
puts "Waiting #{time_left} seconds"
sleep time_left if time_left > 0
reset
else
end
end
def tequila_shot(params)
puts "fucking good"
end
def vodka_shot(params)
puts "fucking good"
end
private
def reset
@calls_count = 0
@invoked_at = nil
end
end
g = GetShots.new(2, 10)
#binding.pry
# run these:
# g.get_shot(:tequila, nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment