Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a gem that normalizes and format US phone numbers in ruby?

I was using phony to format phone numbers (meaning, if I put in xxx-xxx-xxxx it would convert to a string, and also tell if there is a (1) before to remove it).

But it really doesn't work for us phone number, it's designed for international numbers.

Is there an equivalent?

Thanks.

http://rubygems.org/gems/phony

like image 351
Satchel Avatar asked May 06 '11 14:05

Satchel


2 Answers

Earlier this year, I reviewed a bunch of ruby gems that parse and format phone numbers. They fall into a number of groups (see below). TLDR: I used 'phone'. It might work for you because you can specify a default country code that it uses if your phone number doesn't include one.

1) US-centric:

big-phoney (0.1.4)
phone_wrangler (0.1.3)
simple_phone_number (0.1.9)

2) depends on rails or active_record:

phone_number (1.2.0)
validates_and_formats_phones (0.0.7)

3) forks of 'phone' that have been merged back into the trunk:

elskwid-phone (0.9.9.4)
tfe-phone (0.9.9.1)

4) relies on you to know the region ahead of time

phoney (0.1.0)

5) Kind of almost works for me

phone (0.9.9.3)

6) does not contain the substring 'phone' in the gem name (edit: I see you tried this one)

phony (1.6.1)

These groupings may be somewhat unfair or out of date so feel free to comment. I must admit I was a little frustrated at the time at how many people had partially re-invented this particular wheel.

like image 123
Jason McLaren Avatar answered Nov 15 '22 15:11

Jason McLaren


I've never seen much in the way of a reliable telephone number formatter because it's just so hard to get it right. Just when you think you've seen everything, some other format comes along and wrecks it.

Ten digit North American numbers are perhaps the easiest to format, you can use a regular expression, but as soon as you encounter extensions you're in trouble. Still, you can kind of hack it yourself if you want:

def formatted_number(number)
  digits = number.gsub(/\D/, '').split(//)

  if (digits.length == 11 and digits[0] == '1')
    # Strip leading 1
    digits.shift
  end

  if (digits.length == 10)
    # Rejoin for latest Ruby, remove next line if old Ruby
    digits = digits.join
    '(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
  end
end

This will just wrangle eleven and ten digit numbers into the format you want.

Some examples:

formatted_number("1 (703) 451-5115")
 # => "(703) 451-5115"
formatted_number("555-555-1212")
 # => "(555) 555-1212"
like image 27
tadman Avatar answered Nov 15 '22 13:11

tadman