Class: Fredric::API

Inherits:
WebAPI show all
Defined in:
lib/fredric/api.rb

Overview

Provides access to all the FRED API endpoints

Instance Attribute Summary collapse

Attributes inherited from WebAPI

#after_request_block, #base_url, #debug, #format, #last_error

Instance Method Summary collapse

Methods inherited from WebAPI

#after_request, #cache, #construct_url, #default_params, #get, #get!, #method_missing, #param, #save

Constructor Details

#initialize(api_key, opts = {}) ⇒ API

Returns a new instance of API.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fredric/api.rb', line 9

def initialize(api_key, opts={})
  @api_key = api_key

  defaults = {
    use_cache: false,
    cache_dir: nil,
    cache_life: nil,
    base_url: "https://api.stlouisfed.org/fred"
  }

  opts = defaults.merge! opts
  @opts = opts

  cache.disable unless opts[:use_cache]
  cache.dir = opts[:cache_dir] if opts[:cache_dir]
  cache.life = opts[:cache_life] if opts[:cache_life]

  param api_key: api_key if api_key
  param file_type: :json

  after_request do |response| 
    begin
      JSON.parse response, symbolize_names: true
    rescue JSON::ParserError
      response
    end
  end
  
  super opts[:base_url]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Fredric::WebAPI

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



7
8
9
# File 'lib/fredric/api.rb', line 7

def api_key
  @api_key
end

#optsObject (readonly)

Returns the value of attribute opts.



7
8
9
# File 'lib/fredric/api.rb', line 7

def opts
  @opts
end

Instance Method Details

#get_csv(*args) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/fredric/api.rb', line 40

def get_csv(*args)
  response = get(*args)

  raise Fredric::BadResponse, "API said '#{response}'" if response.is_a? String
  raise Fredric::BadResponse, "Got a #{response.class}, expected a Hash" unless response.is_a? Hash
  
  data = csv_node response

  header = data.first.keys
  result = CSV.generate do |csv|
    csv << header
    data.each { |row| csv << row.values }
  end

  result
end

#save_csv(file, *args) ⇒ Object



57
58
59
60
# File 'lib/fredric/api.rb', line 57

def save_csv(file, *args)
  data = get_csv(*args)
  File.write file, data
end