Class: CensusApi::Request

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

Constant Summary collapse

CENSUS_URL =
"http://api.census.gov/data"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, vintage, source, options) ⇒ Request

Returns a new instance of Request.



15
16
17
18
19
20
21
# File 'lib/census_api/request.rb', line 15

def initialize(url, vintage, source, options)
  path = "#{url}/#{vintage}/#{source}?#{options.to_params}"
  @response = RestClient.get(path) do |response, request, result, &block|
    response
  end
  return @response
end

Instance Attribute Details

#responseObject

Returns the value of attribute response.



9
10
11
# File 'lib/census_api/request.rb', line 9

def response
  @response
end

Class Method Details

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



24
25
26
27
28
29
30
31
32
33
# File 'lib/census_api/request.rb', line 24

def self.find(source, options = {})
  fields = options[:fields]
  fields = fields.split(",").push("NAME").join(",") if fields.kind_of? String
  fields = fields.push("NAME").join(",") if fields.kind_of? Array
  params = { :key => options[:key], :get => fields, :for => format(options[:level],false) }
  params.merge!({ :in => format(options[:within][0],true) }) if !options[:within].empty?
  options.merge!({ :vintage => 2010 }) unless options[:vintage]
  request = new(CENSUS_URL, options[:vintage], source, params)
  request.parse_response
end

Instance Method Details

#parse_responseObject



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

def parse_response
  case @response.code
    when 200
      response = JSON.parse(@response)
      header = response.delete_at(0)
      return response.map{|r| Hash[header.map{|h| h.gsub("NAME","name")}.zip(r)]}
    else
      return {:code => @response.code, :message=> "Invalid API key or request", :location=> @response.headers[:location], :body => @response.body}
    end
end