Class: APICache::API
- Inherits:
-
Object
- Object
- APICache::API
- Defined in:
- lib/api_cache/api.rb
Overview
Wraps up querying the API.
Ensures that the API is not called more frequently than every period
seconds, and times out API requests after timeout
seconds.
Instance Method Summary collapse
-
#get ⇒ Object
Fetch data from the API.
-
#initialize(key, options, &block) ⇒ API
constructor
Takes the following options.
Constructor Details
#initialize(key, options, &block) ⇒ API
Takes the following options
- period
-
Maximum frequency to call the API. If set to 0 then there is no limit on how frequently queries can be made to the API.
- timeout
-
Timeout when calling api (either to the proviced url or excecuting the passed block)
- block
-
If passed then the block is excecuted instead of HTTP GET against the provided key
19 20 21 22 23 |
# File 'lib/api_cache/api.rb', line 19 def initialize(key, , &block) @key, @block = key, block @timeout = [:timeout] @period = [:period] end |
Instance Method Details
#get ⇒ Object
Fetch data from the API.
If no block is given then the key is assumed to be a URL and which will be queried expecting a 200 response. Otherwise the return value of the block will be used.
This method can raise Timeout::Error, APICache::InvalidResponse, or any exception raised in the block passed to APICache.get
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/api_cache/api.rb', line 34 def get check_queryable! APICache.logger.debug "APICache #{@key}: Calling API" set_queried_at Timeout::timeout(@timeout) do if @block # If this call raises an error then the response is not cached @block.call else get_key_via_http end end rescue Timeout::Error => e raise APICache::TimeoutError, "APICache #{@key}: Request timed out (timeout #{@timeout}s)" end |