Mel
Mel

Reputation: 2685

Rails: Phone numbers - international prefix

I am using countries gem and country-select gem.

I have an attribute in my phones table called :country_code. I ask users in the new phone form to pick their country:

<%= f.input :country_code,  label: false, wrapper: :vertical_input_group  do %>
  <span class="input-group-addon">Country</span>
  <%= country_select("phone", "country_code", {priority_countries["AU", "GB", "NZ"], selected: "AU" }, class: "form-control" ) %>
<% end %>

I want to take that country and get the international prefix.

I have a phones model, which I have:

def landline_number
   [international_code, area_code, phone_number].join('   ')
end

def international_code
   self.country_code = ISO3166::Country[country_code]
   country_code.translations[I18n.locale.to_s] || country_code.international_prefix
end

When I try:

<%= @phone.landline_number %>

It prints the country name instead of the international prefix.

How do I get it to print a number instead of country name?

Upvotes: 0

Views: 4711

Answers (1)

Jose
Jose

Reputation: 601

It seems to me that your problem is this line:

country_code.translations[I18n.locale.to_s] || country_code.international_prefix

according to the documentation examples

# Get a specific translation
c.translation('de') #=> 'Vereinigte Staaten von Amerika'
c.translations['fr'] #=> "États-Unis"

ISO3166::Country.translations             # {"DE"=>"Germany",...}
ISO3166::Country.translations('DE')       # {"DE"=>"Deutschland",...}

you are actually extracting the country's name first and since it's found the code

country_code.international_prefix

is not executed due to the || condition you have. If you would remove the code to the left of the || it should work. In other words try leaving your method like this:

def international_code
    self.country_code = ISO3166::Country[country_code]
    country_code.international_prefix
end

Upvotes: 1

Related Questions