使用 ruby 和 sinatra,以及 Phony gem 如何从 phone 号码中找到 alpha2 代码?

using ruby and sinatra, and the Phony gem how can I find the alpha2 code from a phone number?

我有一个国际号码作为字符串,所以 81312345678(日本,东京号码)或 85212345678(香港)我需要隔离国家代码,日本是 81,香港是 852 Kong,以便识别国家的 2 字母 alpha2 代码。

我试过假 gem 如下:

number = Phony.format('18091231234', :format => :international)
  puts number
  split = Phony.split('85212345678')
  puts split[0]

以香港为例,我现在想输入“852”并获取香港的 2 个字母的国家/地区代码,以便使用 Plivo api 查找定价。

产生:

+1 809 123 1234
852

我试过 'iso_country_codes' gem 失败,'countries' gem 有:

c = Country.find_country_by_national_prefix('852')
  puts c.alpha2

错误信息是'undefined method alpha2'这应该很容易。有什么想法吗?一如既往的感谢。

稍加测试,香港的 national_prefix 值(在 countries gem 中)似乎是 "None"。您可能想像这样使用 Country#find_country_by_country_codeCountry.find_country_by_country_code('852'),这将 return 香港,然后您可以调用 #alpha2

附带说明一下,在尝试调用 alpha2 之前,您可能需要检查 c 不是 nil

虽然 "phony" gem 仍然非常有用,但我尝试使用 "countries" gem 和 "iso_country_codes" gem困难和部分成功,所以我最终从 Plivo 网站(超过 38,000 行)下载定价数据并将其加载到 postgres 数据库中。

一列是 country_code,另一列是前缀列。在某些情况下,您只需要 country_code 而在其他情况下需要 country_code 和前缀才能获得精确的结果。所以,这是代码:

get '/iso' do
    number = '447928xxxxxx' #this is a mobile so you need both 44 and 7928
    code = Phony.split(number)
    lookup = code.take(2).join #joins the first 2 elements of the array
    result = DB[:call_pricing].where(:prefix=>lookup).get(:rate_usd)
    if result.nil?
      lookup = code.take(1) 
    result = DB[:call_pricing].where(:prefix=>lookup).get(:rate_usd)
    end
end

我希望这对其他人有所帮助。