Class: ImHungry::FetchJson

Inherits:
Object
  • Object
show all
Defined in:
lib/im_hungry/fetch_json.rb

Class Method Summary collapse

Class Method Details

.fetch(url, model) ⇒ Object



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
# File 'lib/im_hungry/fetch_json.rb', line 6

def self.fetch(url, model)
  uri = URI.parse(url)
  req = Net::HTTP::Get.new(uri)
  res = Net::HTTP.start(uri.host, uri.port) do |http|
    http.request(req)
  end
  raise "HTTP code #{res.code} - Failure fetching json" if res.code != '200'
  self.to_model(res.body, model)
rescue SocketError
  puts 'Network connectivity issue'
  exit
rescue Errno::ECONNREFUSED => e
  puts 'The server is down.'
  puts e.message
  exit
rescue Timeout::Error => e
  puts 'Timeout error occurred.'
  puts e.message
  exit
rescue Errno::EINVAL, Errno::ECONNRESET, EOFError,
       Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
       Net::ProtocolError => e
  puts 'Error occurred.'
  puts e.message
  exit
end

.to_model(body, model) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/im_hungry/fetch_json.rb', line 33

def self.to_model(body, model)
  JSON.parse(body).map do |food_truck_json|
    model.new(food_truck_json)
  end
rescue JSON::ParserError => e
  puts 'Invalid JSON'
  puts e.message
  exit
end