Search code examples
rubysinatraplivo

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


I have an international number as a string, so 81312345678 (Japan, Tokyo number) or 85212345678 (Hong Kong) and I need to isolate the country code, 81 in the case of Japan and 852 in the case of Hong Kong, in order to then identify the 2 letter alpha2 code of the country.

I have tried the phony gem as follows:

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

In the case of Hong Kong, for example, I would now like to take '852' and get the 2 letter country code for Hong Kong in order to then look up pricing using the Plivo api.

which produces:

+1 809 123 1234
852

I have tried the 'iso_country_codes' gem unsuccessfully and the 'countries' gem with:

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

The error message is 'undefined method alpha2' this should be easy. Any ideas guys? Thanks as always.


Solution

  • With a little testing, it looks like the national_prefix value (in the countries gem) of Hong Kong is "None". You may want to use Country#find_country_by_country_code like so: Country.find_country_by_country_code('852') and that will return Hong Kong, which you can then call #alpha2 on.

    On a side note, you may want to check that c is not nil before trying to call alpha2 on it.