Class: Census::ResultSet

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

Overview

A result data set

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json = '[]') ⇒ ResultSet

Constructs a new data object from Census data returned by the API. The format of JSON should be:

[["column1", "column2", ...], [row11, row12, ...], [row21, row22, ...], ...]


163
164
165
166
167
168
169
# File 'lib/rboc/data.rb', line 163

def initialize(json='[]')
  json = JSON.parse json if json.is_a? String
  @colnames, *@rows = *json
  @colmap = Hash[@colnames.zip (0..@colnames.length)]

  @geocolnames, @datacolnames = self.class.split_colnames colnames
end

Instance Attribute Details

#colnamesObject (readonly)

Returns the value of attribute colnames.



157
158
159
# File 'lib/rboc/data.rb', line 157

def colnames
  @colnames
end

#rowsObject (readonly)

Returns the value of attribute rows.



157
158
159
# File 'lib/rboc/data.rb', line 157

def rows
  @rows
end

Class Method Details

.split_colnames(colnames) ⇒ Object

Split a list of column names into geographic columns and data columns



141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/rboc/data.rb', line 141

def self.split_colnames(colnames)
  geocolnames = []
  datacolnames = []
  colnames.each do |s|
    if Geography::LEVELS.include? s
      geocolnames << s
    else
      datacolnames << s
    end
  end

  [geocolnames, datacolnames]
end

Instance Method Details

#==(other) ⇒ Object



207
208
209
# File 'lib/rboc/data.rb', line 207

def ==(other)
  other.is_a?(ResultSet) && self.colnames == other.colnames && self.rows == other.rows
end

#eachObject



171
172
173
174
175
# File 'lib/rboc/data.rb', line 171

def each
  @rows.each do |row|
    yield Hash[@colnames.zip row]
  end
end

#merge!(json) ⇒ Object

Merges an existing Census data set with additional data returned from the API. Currently, this method assumes columns and rows are returned in a consistent order given the same geography.



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/rboc/data.rb', line 181

def merge!(json)
  json = JSON.parse json if json.is_a? String
  colnames, *rows = *json
  colmap = Hash[colnames.zip (0..colnames.length)]
  geocolnames, datacolnames = self.class.split_colnames colnames

  if geocolnames != @geocolnames
    raise ArgumentError, "Mismatched geographies"
  end

  @rows.map!.with_index do |row, i|
    if  @geocolnames.any? {|s| row[@colmap[s]] != rows[i][colmap[s]]}
      raise ArgumentError, "Mismatched rows"
    end

    row += datacolnames.map {|s| rows[i][colmap[s]]}
  end

  n = @colnames.length
  @colmap.merge! Hash[datacolnames.zip (n..(n+datacolnames.length))]
  @colnames += datacolnames
  @datacolnames += datacolnames

  self
end