Class: Usatoday::Census::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/usatoday-census/base.rb

Direct Known Subclasses

Ethnicity, Housing, Location, Population, Race

Constant Summary collapse

API_SERVER =
"api.usatoday.com"
API_NAME =
"census"
API_BASE =
"/open/#{API_NAME}"
@@api_key =
nil
@@debug =
false
@@decode_html_entities =
true

Class Method Summary collapse

Class Method Details

.api_keyObject



21
22
23
# File 'lib/usatoday-census/base.rb', line 21

def self.api_key
  @@api_key
end

.api_key=(key) ⇒ Object



17
18
19
# File 'lib/usatoday-census/base.rb', line 17

def self.api_key=(key)
  @@api_key = key
end

.build_request_url(method, params) ⇒ Object



25
26
27
28
29
# File 'lib/usatoday-census/base.rb', line 25

def self.build_request_url(method, params)
  URI::HTTP.build :host => API_SERVER, 
  :path => API_BASE + '/' + method, 
  :query => params.map {|k,v| "#{URI.escape(k)}=#{URI.escape(v.to_s)}"}.join('&')
end

.float_field(value) ⇒ Object



41
42
43
44
# File 'lib/usatoday-census/base.rb', line 41

def self.float_field(value)
  return nil if value.nil?
  value.to_f
end

.integer_field(value) ⇒ Object



36
37
38
39
# File 'lib/usatoday-census/base.rb', line 36

def self.integer_field(value)
  return nil if value.nil?
  value.to_i
end

.invoke(method, params = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/usatoday-census/base.rb', line 54

def self.invoke(method, params={})
  begin
    raise AuthenticationError, "You must initialize the API key before you run any API queries" if @@api_key.nil?
    
    full_params = params.merge 'api_key' => @@api_key
    uri = build_request_url(method, full_params)	
    puts "REQUEST: #{uri}" if @@debug
    
    reply = uri.read
    parsed_reply = JSON.parse reply
    
    raise BadResponseError, "Empty reply returned from API" if parsed_reply.nil?
    response = parsed_reply['response']
  rescue OpenURI::HTTPError => e
    case e.message
      when /^400/
        raise BadRequestError
      when /^403/
        raise AuthenticationError
      when /^404/
        return nil
      when /^500/
        raise ServerError
      else
        raise ConnectionError
      end
    raise "Error connecting to URL #{uri} #{e}"
  rescue JSON::ParserError => e
    raise BadResponseError, "Invalid JSON returned from API:\n#{reply}"          
  end
end

.prepare_params(method, keyname = nil, sumlevid = 2) ⇒ Object



46
47
48
49
50
51
# File 'lib/usatoday-census/base.rb', line 46

def self.prepare_params(method, keyname=nil, sumlevid=2)
  params = {"keypat" => method }
  params["keyname"] = keyname if keyname
  params.merge({'sumlevid'=>sumlevid})
  params
end

.text_field(value) ⇒ Object



31
32
33
34
# File 'lib/usatoday-census/base.rb', line 31

def self.text_field(value)
  return nil if value.nil?
  @@decode_html_entities ? HTMLEntities.new.decode(value) : value
end