Module Flight API
require 'open-uri'
module FlightAPI
def self.flights_populate(city)
date = (Date.today + 30).strftime("%Y/%m/%d")
json = JSON.parse(open("https://api.flightstats.com/flex/connections/rest/v1/json/direct/to/#{city.iata_code}/arriving/#{date}?appId=app_id&appKey=api_key").read)
airports = json["appendix"]["airports"]
carriers = json["appendix"]["airlines"]
flights = json["flights"]
flights.each do |f|
a = airports.select{|k| k["fs"] == f["departureAirportFsCode"]}.first
c = carriers.select{|k| k["fs"] == f["flightLegs"].first["carrierFsCode"]}.first
location = a["city"] + ", " + a["countryName"]
Flight.create!(city_id: city.id, location: location, airport: a["name"], longitude: a["longitude"], latitude: a["latitude"], airline: c["name"], flight_time: flight_time(f["flightDurationMinutes"]))
end
end
def self.for_city(city)
destinations = []
city.flights.each do |f|
destinations << { location: f.location, airport: f.airport, coords: [f.longitude, f.latitude], airlines: [f.airline], flight_time: f.flight_time }
end
destinations
end
private
# def self.find_airlines(codes)
# airlines = []
# codes = [codes] if codes.is_a? String
# codes.uniq.each do |c|
# airlines << @csv.find {|airline| airline['iata'] == c || airline['icao'] == c || airline['awb'] == c}
# end
# airlines.collect(&:name) if !airlines.empty?
# end
def self.flight_time(time)
hours = time/60
minutes = time - (hours*60)
"#{hours}hr(s) #{minutes}min(s)"
end
end