1# frozen_string_literal: true
2
3require "delegate"
4require "nokogiri"
5
6class LocalCallingGuideRepo
7 class Prefix < SimpleDelegator
8 # @return [Float]
9 def lat
10 at("rc-lat").text.to_f
11 end
12
13 # @return [Float]
14 def lon
15 at("rc-lon").text.to_f
16 end
17
18 # @return [String]
19 def region
20 at("region").text
21 end
22
23 # @return [String]
24 def locality
25 at("rc").text
26 end
27
28 # @return [Hash<String, String>]
29 def to_h
30 { "region" => region, "locality" => locality }
31 end
32 end
33
34 # @param npa [String] area code (first 3 digits after country code)
35 # @param nxx [String] exchange (digits 4-6)
36 # @return [EMPromise<Prefix>]
37 # @raise [RuntimeError] if no prefix data found
38 def find(npa, nxx)
39 EM::HttpRequest.new(
40 "https://localcallingguide.com/xmlprefix.php",
41 tls: { verify_peer: true }
42 ).aget(query: { npa: npa, nxx: nxx }).then { |res|
43 prefix = Nokogiri::XML.parse(res.response).at("prefixdata")
44 raise "No prefix data for #{npa}-#{nxx}" unless prefix
45
46 Prefix.new(prefix)
47 }
48 end
49end