Skip to content

Instantly share code, notes, and snippets.

@docwhat
Created July 11, 2019 17:25
Show Gist options
  • Save docwhat/8e60f6a3cae84cca7cc40f97e8df759d to your computer and use it in GitHub Desktop.
Save docwhat/8e60f6a3cae84cca7cc40f97e8df759d to your computer and use it in GitHub Desktop.
Check for power outages from Duquesne Light in Pittsburgh.
#!/usr/bin/env ruby -w
# frozen_string_literal: true
require 'json'
require 'open-uri'
require 'date'
class Outage
attr_reader :name, :zip, :lat, :long, :number_affected, :last_updated
def initialize(name, zip, lat, long, number_affected, last_updated)
@name = name.to_s.split(/\s+/).map(&:capitalize).join(' ')
@zip = Integer(zip)
@lat = lat
@long = long
@number_affected = Integer(number_affected)
@last_updated = Time.at(Integer(last_updated.sub(%r{/Date\((\d+)\)/}, '\1')) / 1000).to_datetime
end
def self.from_group(group_data)
muni = group_data['Municipality']
new muni['Name'], muni['Zip'], muni['Latitude'], muni['Longitude'], group_data['Affected'], group_data['LastUpdated']
end
def zip?(zipcode)
Integer(zipcode) == zip
end
def to_s
"#{name} (#{zip}) has #{number_affected} people without power as of #{last_updated.strftime('%c')}"
end
end
class Outages
API_URI = 'https://duquesnelight.com/outages-safety/current-outages/GetReportedOutages/'
API_URI_CACHE = File.join(ENV['TMPDIR'] || '/tmp/', 'duquesnelight-outages.json')
def initialize
File.write(API_URI_CACHE, JSON.pretty_generate(JSON.parse(open(API_URI).read)) + "\n") unless File.exist? API_URI_CACHE
@data = JSON.parse(open(API_URI_CACHE).read)
end
def outages
@outages ||= @data['OutageGroups'].map { |group| Outage.from_group group }
end
def zip(zipcode)
outages.select { |o| o.zip? zipcode }
end
def name(needle)
outages.each { |o| [o.name, needle].join(' - ') }
outages.select { |o| o.name.downcase.include? needle.downcase }
end
end
outages = Outages.new
puts begin
outages.zip(Integer(ARGV.first))
rescue ArgumentError
outages.name(String(ARGV.first))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment