Skip to content

Instantly share code, notes, and snippets.

@micmmakarov
Last active October 12, 2016 00:12
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 micmmakarov/101a3f555ee15f3f13d7bcb888cdeeac to your computer and use it in GitHub Desktop.
Save micmmakarov/101a3f555ee15f3f13d7bcb888cdeeac to your computer and use it in GitHub Desktop.
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