Module: OnsOpenApi::Connection

Included in:
OnsOpenApi
Defined in:
lib/ons_openapi/connection.rb

Constant Summary collapse

BASE_URI =
'http://data.ons.gov.uk/ons/api/data/'
API_KEY =
ENV['ONS_APIKEY']

Instance Method Summary collapse

Instance Method Details

#get(resource, args = {}) ⇒ Object



8
9
10
# File 'lib/ons_openapi/connection.rb', line 8

def get(resource, args={})
  to_object request(resource, "get", args)
end

#post(resource, args = {}) ⇒ Object



12
13
14
# File 'lib/ons_openapi/connection.rb', line 12

def post(resource, args={})
  to_object request(resource, "post", args)
end

#request(resource, method = "get", args) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ons_openapi/connection.rb', line 41

def request(resource, method="get", args)
  uri = request_uri resource, args
  case method
  when "get"
    req = Net::HTTP::Get.new(uri.request_uri)
  when "post"
    req = Net::HTTP::Post.new(uri.request_uri)
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.port == 443)

  res = http.start() { |conn| conn.request(req) }
  res.body
end

#request_uri(resource, args) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ons_openapi/connection.rb', line 26

def request_uri(resource, args)
  unless API_KEY
    raise 'No ONS OpenAPI key found. Set this environment variable: ONS_APIKEY=<your_ons_openapi_key>'
  end
  uri = URI.join(BASE_URI, (resource+'.json').sub('.json.json','.json') )

  args ||= {}
  args.delete('apikey')
  args.merge!( apikey: API_KEY )
  uri.query = args.map { |k,v| "%s=%s" % [URI.encode(k.to_s), URI.encode(v.to_s)] }.join("&") if args

  puts uri.to_s
  uri
end

#to_object(json) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/ons_openapi/connection.rb', line 16

def to_object json
  json.gsub!('"@', '"')
  json.gsub!('xml.lang','xml_lang')
  json.gsub!('"$":','"text":')
  json.gsub!('"2011WARDH" : {', '"X2011WARDH" : {')
  json.gsub!('"2011HTWARDH" : {', '"X2011HTWARDH" : {')
  hash = JSON.parse json
  Morph.from_hash hash, OnsOpenApi
end