Class: Census::DataSetVintage

Inherits:
Object
  • Object
show all
Defined in:
lib/rboc/data.rb

Overview

Create one DataSetVintage object per data set description in the discovery API.

Constant Summary collapse

MEMBER_VARS =

a map from API json variables to member variables

{
  :vintage => 'c_vintage',
  :dataset => 'c_dataset',
  :geography_link => 'c_geographyLink',
  :variables_link => 'c_variablesLink',
  :is_aggregate => 'c_isAggregate',
  :title => 'title',
  :web_service => 'webService',
  :access_level => 'accessLevel',
  :contact_point => 'contactPoint',
  :description => 'description',
  :identifier => 'identifier',
  :mbox => 'mbox',
  :publisher => 'publisher',
  :references => 'references',
  :spatial => 'spatial',
  :temporal => 'temporal'
}

Instance Method Summary collapse

Constructor Details

#initialize(json) ⇒ DataSetVintage

Returns a new instance of DataSetVintage.



33
34
35
36
37
38
39
40
41
# File 'lib/rboc/data.rb', line 33

def initialize(json)
  MEMBER_VARS.each do |var, key|
    v = ('@' + var.to_s).to_sym
    self.instance_variable_set v, json[key]
  end

  # 'vintage' should be an int
  @vintage = @vintage.to_i
end

Instance Method Details

#query(q = Query.new) {|q| ... } ⇒ Object

Accesses the the data api and parses the result into a Census::Data object.

Yields:

  • (q)


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/rboc/data.rb', line 73

def query(q=Query.new)
  yield q if block_given?

  # download the first 50 or fewer variables
  json = self.query_raw q[0...50]
  rs = ResultSet.new json

  # download remaining variables 50 at a time
  offset = 50
  while offset <= q.variables.length
    json = self.api_raw year, file, q[offset...(offset+50)]
    json = JSON.parse json

    # sometimes the API returns a descriptive hash (in a single element array) if the
    # requested columns are invalid
    raise InvalidQueryError if json.first.is_a? Hash

    rs.merge! json
    offset += 50
  end

  rs
end

#query_raw(q = Query.new) {|q| ... } ⇒ Object

Accesses the data api and returns the unmodified body of the HTTP response. Raises errors if the HTTP response code indicates a problem.

Yields:

  • (q)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rboc/data.rb', line 46

def query_raw(q=Query.new)
  yield q if block_given?

  url = self.web_service + '?' + q.to_s
  puts "GET #{url}"

  c = Curl::Easy.new url
  c.perform
  r = c.response_code

  if r == 200
    return c.body_str
  elsif r == 400
    raise InvalidQueryError
  elsif r == 204
    raise NoMatchingRecordsError
  elsif r == 500
    raise ServerSideError
  elsif r == 302 && (c.head.include?("missing_key") || c.head.include?("invalid_key"))
    raise InvalidKeyError
  else
    raise CensusApiError, "Unexpected HTTP response code: #{r}"
  end
end