Class: APICache::API
- Inherits:
-
Object
- Object
- APICache::API
- Defined in:
- lib/api_cache/api.rb
Overview
This class wraps up querying the API and remembers when each API was last queried in case there is a limit to the number that can be made.
Instance Method Summary collapse
-
#get(key, timeout, &block) ⇒ Object
Fetch data from the API.
-
#initialize ⇒ API
constructor
A new instance of API.
-
#queryable?(key, retry_time) ⇒ Boolean
Checks whether the API can be queried (i.e. whether retry_time has passed since the last query to the API).
Constructor Details
#initialize ⇒ API
6 7 8 |
# File 'lib/api_cache/api.rb', line 6 def initialize @query_times = {} end |
Instance Method Details
#get(key, timeout, &block) ⇒ 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.
If the block is unable to fetch the value from the API it should raise APICache::Invalid.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/api_cache/api.rb', line 38 def get(key, timeout, &block) APICache.logger.log "Fetching data from the API" @query_times[key] = Time.now Timeout::timeout(timeout) do if block_given? # This should raise APICache::Invalid if it is not correct yield else get_via_http(key, timeout) end end rescue Timeout::Error, APICache::Invalid => e raise APICache::CannotFetch, e. end |
#queryable?(key, retry_time) ⇒ Boolean
Checks whether the API can be queried (i.e. whether retry_time has passed since the last query to the API).
If retry_time is 0 then there is no limit on how frequently queries can be made to the API.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/api_cache/api.rb', line 15 def queryable?(key, retry_time) if @query_times[key] if Time.now - @query_times[key] > retry_time APICache.logger.log "Queryable: true - retry_time has passed" true else APICache.logger.log "Queryable: false - queried too recently" false end else APICache.logger.log "Queryable: true - never used API before" true end end |