Class: CensusApi::Client

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

Constant Summary collapse

SUMMARY_LEVELS =
{}
DATASETS =

can add more datasets as support becomes available

%w( sf1 acs5 )

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, options = {}) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


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

def initialize(api_key, options = {})
  raise ArgumentError, "You must set an api_key." unless api_key

  # Use RestClient directly to determine the validity of the API Key
  path = "http://api.census.gov/data/2010/sf1?key=#{api_key}&get=P0010001&for=state:01"
  response = RestClient.get(path)

  if response.body.include? "Invalid Key"
    raise "'#{api_key}' is not a valid API key. Check your key for errors, or request a new one at census.gov."
  end

  @api_key = api_key
  if options[:dataset]
    @dataset = options[:dataset].downcase if DATASETS.include? options[:dataset].downcase
  end

  set_summary_levels
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



6
7
8
# File 'lib/census_api/client.rb', line 6

def api_key
  @api_key
end

#datasetObject

Returns the value of attribute dataset.



7
8
9
# File 'lib/census_api/client.rb', line 7

def dataset
  @dataset
end

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/census_api/client.rb', line 6

def options
  @options
end

Instance Method Details

#find(fields, level, *within) ⇒ Object



31
32
33
34
# File 'lib/census_api/client.rb', line 31

def find(fields, level, *within)
  raise "Client has not been assigned a dataset to query. Try @client.dataset = 'SF1' or anything from #{DATASETS}" if self.dataset.nil?
  Request.find(dataset, {key: @api_key, fields: fields, level: level, within: within})
end

#set_summary_levelsObject



36
37
38
39
40
# File 'lib/census_api/client.rb', line 36

def set_summary_levels
  if SUMMARY_LEVELS.empty?
    YAML.load_file(File.dirname(__FILE__).to_s + '/../yml/census_shapes.yml').each{ |k,v| SUMMARY_LEVELS[k] = v }
  end
end