-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.rb
75 lines (62 loc) · 1.8 KB
/
test.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'ap'
module USDA
require 'uri'
require 'net/http'
require 'json'
class API
attr_accessor :base_uri
API_KEY = { api_key: "DEMO_KEY" }
def initialize(base_uri = "http://api.data.gov/USDA/ERS/data/")
@base_uri = base_uri
end
def response(endpoint, params = {})
uri = build_uri(endpoint, params)
response = Net::HTTP.get(uri)
JSON.parse(response)
end
def build_uri(endpoint, params)
params.merge!(API_KEY)
uri = URI(@base_uri + endpoint)
uri.query = URI.encode_www_form(params)
uri
end
end
class ARMS
def self.surveys
api = API.new
api.response("Arms/Surveys")
end
def self.reports(survey)
api = API.new
api.response("Arms/Reports", survey: survey)
end
def self.subjects(survey, report)
api = API.new
api.response("Arms/Subjects", survey: survey, report: report)
end
def self.series(survey, report)
api = API.new
api.response("Arms/Series", survey: survey, report: report)
end
def self.crops(report, series, options = {})
options_hash = { report: report, series1: series }.merge options
api = API.new
api.response("Arms/Crop", options_hash)
end
end
class Selector
def self.select_from_results(selectors = {}, results)
selected = results["dataTable"]
selectors.each do |selector, value|
selected = selected.select { |e| e[selector] == value }
end
selected
end
end
class DataSeries
def self.data_by_year(topic_seq, subject_num, element2_name, results)
selected = Selector.select_from_results({ "topic_seq" => topic_seq, "subject_num" => subject_num, "element2_name" => element2_name }, results)
selected.map { |n| { n["stat_year"] => n["estimate"] } }
end
end
end