Skip to content

Instantly share code, notes, and snippets.

@ambethia
Last active August 29, 2015 14:06
Show Gist options
  • Save ambethia/91afe9ee990d83bc2ad9 to your computer and use it in GitHub Desktop.
Save ambethia/91afe9ee990d83bc2ad9 to your computer and use it in GitHub Desktop.
Throttle Hack
class Book
extend Throttle
def self.sales_rank(isbn_13)
throttle(1.second) do
# Do stuff with Amazon Product API that's rate limited to 1 req/s.
end
end
end
module Throttle
# Terrible, awful, blocking, not thread-safe throttle
def throttle(duration)
@_last_throttled ||= duration.ago
now = Time.now
elapsed = now - @_last_throttled
sleep(duration - elapsed) if elapsed < duration
@_last_throttled = Time.now
return yield
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment