Last active
August 29, 2015 14:06
-
-
Save ambethia/91afe9ee990d83bc2ad9 to your computer and use it in GitHub Desktop.
Throttle Hack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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