Method: OnsOpenApi::Collection#data
- Defined in:
- lib/ons_openapi/collection.rb
#data(geog_code, geog, stat = '.toTable()') ⇒ Object
Returns data for given geog_code, geog, and optional JSON-stat command.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/ons_openapi/collection.rb', line 27 def data geog_code, geog, stat='.toTable()' @json_stats ||={} @json_stats[geog_code + geog] ||= OnsOpenApi::request("dataset/#{id}", context: context_name, geog: geog, "dm/#{geog}" => geog_code, totals: 'false', jsontype: 'json-stat') raw_json_stat = @json_stats[geog_code + geog].gsub("\n", ' ').gsub("'", "").squeeze(' ') if raw_json_stat.include?('ns1faultstring') raise "ONS Exception: #{raw_json_stat.gsub(/(<.?ns1XMLFault>)|(<.?ns1faultstring>)/,'')}" elsif raw_json_stat.include?('errorMessage') raise "ONS Error: #{raw_json_stat}" end begin table = js_context.eval( %Q| JSONstat( JSON.parse(' #{raw_json_stat} ') ).Dataset(0)#{stat} | ) rescue Encoding::UndefinedConversionError => e if e.to_s[/ASCII-8BIT to UTF-8/] raw_json_stat = raw_json_stat.force_encoding('ASCII-8BIT').encode('UTF-8', :invalid => :replace, :undef => :replace, :replace => '?') table = js_context.eval( %Q| JSONstat( JSON.parse(' #{raw_json_stat} ') ).Dataset(0)#{stat} | ) else raise "#{e.to_s}: #{raw_json_stat}" end rescue ExecJS::RuntimeError, ExecJS::ProgramError => e raise "#{e.to_s}: #{raw_json_stat}" end if table.is_a?(Array) && (index = table[1].index('Segment_1')) table.each {|row| row.delete_at(index)} end table end |