Class: APICache::API

Inherits:
Object
  • Object
show all
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)

Constructor Details

- (API) initialize(key, options, &block)

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, options, &block)
  @key, @block = key, block
  @timeout = options[:timeout]
  @period = options[:period]
end

Instance Method Details

- (Object) get

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