Class: CensusApi::Request
- Inherits:
-
Object
- Object
- CensusApi::Request
- Defined in:
- lib/census_api/request.rb
Constant Summary collapse
- CENSUS_URL =
"http://api.census.gov/data/2010"
Instance Attribute Summary collapse
-
#response ⇒ Object
Returns the value of attribute response.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(url, source, options) ⇒ Request
constructor
A new instance of Request.
- #parse_response ⇒ Object
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, ) path = "#{url}/#{source}?#{options.to_params}" @response = RestClient.get(path) do |response, request, result, &block| response end return @response end |
Instance Attribute Details
#response ⇒ Object
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, = {}) fields = [:fields] fields = fields.split(",").push("NAME").join(",") if fields.kind_of? String fields = fields.push("NAME").join(",") if fields.kind_of? Array params = { :key => [:key], :get => fields, :for => format([:level],false) } params.merge!({ :in => format([:within][0],true) }) if ![: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_response ⇒ Object
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 |