1require 'faraday' |
|
2require 'postcode_sanitizer' |
|
4class Constituency < ActiveRecord::Base |
|
5 class ApiClient |
|
6 HOST = 'http://data.parliament.uk' |
|
7 ENDPOINT = '/membersdataplatform/services/mnis/Constituencies/%{postcode}/' |
|
8 TIMEOUT = 5 |
|
10 def call(postcode) |
|
11 faraday.get(path(postcode)) do |request| |
|
12 request.options[:timeout] = TIMEOUT |
|
13 request.options[:open_timeout] = TIMEOUT |
|
14 end |
|
15 end |
|
17 private
|
|
19 def faraday |
|
20 @faraday ||= Faraday.new(HOST) do |f| |
|
21 f.response :follow_redirects |
|
22 f.response :raise_error |
|
23 f.adapter :net_http_persistent |
|
24 end |
|
25 end |
|
27 def path(postcode) |
|
28 ENDPOINT % { postcode: escape_path(postcode) } |
|
29 end |
|
31 def escape_path(value) |
|
32 Rack::Utils.escape_path(sanitize(value)) |
|
33 end |
|
35 def sanitize(value) |
|
36 PostcodeSanitizer.call(value) |
|
37 end |
|
38 end |
|
39end |