Class: CensusApi::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/census_api/request.rb

Overview

> CensusApi::Request

client#initialize method takes an url, vintage, source, options hash. client#find method accepts source and options hash, which include :key, :fields, :level, :within and :vintage.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vintage, source, options) ⇒ Request

Returns a new instance of Request.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/census_api/request.rb', line 13

def initialize(vintage, source, options)
  api_changes = [
    {source: 'acs1', from: 2012, to: 2015, new_endpoint: 'acs/acs1'},
    #{source: 'acs3', from: 2012, to: 2013, new_endpoint: 'acs/acs3'},
    {source: 'acs5', from: 2010, to: 2015, new_endpoint: 'acs/acs5'},
    {source: 'acsse', from: 2014, to: 2015, new_endpoint: 'acs/acsse'},
    {source: 'sf1', from: 2010, to: 2010, new_endpoint: 'dec/sf1'}
  ]
  route = api_changes.detect do |a| 
    a[:source] == source && a[:from] <= vintage.to_i && a[:to] >= vintage.to_i
  end
  if route
    source = route[:new_endpoint]
  end
  uri = "/data/#{vintage}/#{source}?#{to_params(options)}"
  @response = $census_connection.get(uri.to_s)
  @response.flush
end

Instance Attribute Details

#responseObject

Returns the value of attribute response.



11
12
13
# File 'lib/census_api/request.rb', line 11

def response
  @response
end

Class Method Details

.find(source, options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/census_api/request.rb', line 32

def self.find(source, options = {})
  fields = options[:fields]
  fields = fields.split(',').push('NAME').join(',') if fields.is_a? String
  fields = fields.push('NAME').join(',') if fields.is_a? Array
  level  = format(options[:level])
  params = { get: fields, for: level }
  unless options[:within].nil? || (options[:within].is_a?(Array) && options[:within].empty?)
    params.merge!(in: format(options[:within].join("+")))
  end
  options.merge!(vintage: 2010) unless options[:vintage]
  params.merge!(key: options[:key]) if !!(options[:key])
  request = new(options[:vintage], source, params)
  request.parse_response
end

Instance Method Details

#parse_responseObject



47
48
49
50
51
52
53
54
# File 'lib/census_api/request.rb', line 47

def parse_response
  case @response.code
  when 200
    response_success(@response)
  else
    response_error(@response)
  end
end

#to_params(options) ⇒ Object



56
57
58
# File 'lib/census_api/request.rb', line 56

def to_params(options)
  options.map { |k,v| "#{k}=#{v}" }.join("&")
end