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/2010"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, source, options) ⇒ Request



12
13
14
15
16
17
18
# File 'lib/census_api/request.rb', line 12

def initialize(url, source, options)
  path = "#{url}/#{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.



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

def response
  @response
end

Class Method Details

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



21
22
23
24
25
26
27
28
29
# File 'lib/census_api/request.rb', line 21

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?
  request = new(CENSUS_URL, source, params)
  request.parse_response
end

.format(str, truncate) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/census_api/request.rb', line 45

def self.format(str,truncate)
  result = str.split("+").map{|s|
    if s.match(":")
      s = s.split(":")
    else 
      s = [s,"*"]
    end
    shp = CensusApi::Client::SUMMARY_LEVELS[s[0].upcase]
    s.shift && s.unshift(shp['name'].downcase.gsub(" ", "+")) if !shp.nil?
    s.unshift(s.shift.split("/")[0]) if !s[0].scan("home+land").empty? && truncate
    s.join(":")
  }
  return result.join("+")
end

Instance Method Details

#parse_responseObject



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

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