Jorge Cuevas
Jorge Cuevas

Reputation: 774

How to format number_to_phone for another country in Rails 4?

I'm having some issues with number formatting in rails.

I tried some suggestions from the community when working with string formatting and also the documentation resources:

http://edgeapi.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_phone

The thing I tried were these:

<%= number_to_phone(client.phone, {:groupings => [4,3,3], delimiter: "-"}) %>

and

<%= number_to_phone(client.phone, pattern: /(\d{2})(\d{5})(\d{5})$/)) %>

None of these turned out to work for me even though the documentations states:

Formats a number into a phone number (US by default e.g., (555) 123-9876). You can customize the format in the options hash.

and the example provided is:

number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/))

=> "133-1234-5678"

I want to format it like this:

(12)-3456-7890

What am I missing so this code works the way I expect?

Upvotes: 3

Views: 1685

Answers (2)

jmschles
jmschles

Reputation: 274

You could always write your own helper method if you want to:

def num_to_phone(num)
  "(#{ num[0..1] })-#{ num[2..5] }-#{ num[6..-1] }"
end

Upvotes: 4

Matouš Bor&#225;k
Matouš Bor&#225;k

Reputation: 15944

The :pattern option has been only added to Rails 5.0.0 rc1. It won't work in Rails 4. So I guess you are out of luck unless you update to Rails 5.

Upvotes: 3

Related Questions