demarches-normaliennes/app/lib/api_geo/api.rb

45 lines
947 B
Ruby
Raw Normal View History

2018-10-15 21:01:37 +02:00
class ApiGeo::API
2018-10-23 15:35:03 +02:00
TIMEOUT = 15
2018-10-15 17:26:06 +02:00
def self.regions
url = [API_GEO_URL, "regions"].join("/")
2018-10-23 15:35:03 +02:00
call(url, { fields: :nom })
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-15 17:26:06 +02:00
def self.departements
url = [API_GEO_URL, "departements"].join("/")
2018-10-23 15:35:03 +02:00
call(url, { fields: :nom })
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-15 17:26:06 +02:00
def self.pays
2018-10-23 15:35:03 +02:00
parse(File.open('app/lib/api_geo/pays.json').read)
2018-10-15 17:26:06 +02:00
end
2018-10-15 16:30:27 +02:00
2018-10-15 17:26:06 +02:00
private
2018-10-15 16:30:27 +02:00
2018-10-23 15:35:03 +02:00
def self.parse(body)
JSON.parse(body, symbolize_names: true)
end
def self.call(url, body, method = :get)
response = Typhoeus::Request.new(
url,
method: method,
params: method == :get ? body : nil,
body: method == :post ? body : nil,
timeout: TIMEOUT,
accept_encoding: 'gzip',
headers: {
'Accept' => 'application/json',
'Accept-Encoding' => 'gzip, deflate'
}.merge(method == :post ? { 'Content-Type' => 'application/json' } : {})
).run
if response.success?
parse(response.body)
else
nil
end
2018-10-15 16:30:27 +02:00
end
end