Skip to content

Instantly share code, notes, and snippets.

@davidteren
Last active March 22, 2021 07:24
Show Gist options
  • Save davidteren/1abfbc4d92c9547ccfdda870ca7b18b0 to your computer and use it in GitHub Desktop.
Save davidteren/1abfbc4d92c9547ccfdda870ca7b18b0 to your computer and use it in GitHub Desktop.
Example for using the phonelib gem.
# Using the 'phonelib' gem as it's based on Googles libphonenumber library.
# https://github.com/daddyz/phonelib
require 'phonelib'
require 'active_support'
# Set South Africa as the default country
Phonelib.default_country = "ZA"
Phonelib.extension_separate_symbols = ["x", ";"]
def normalize_phone(phone)
Phonelib.parse(phone).full_e164.presence
end
def formatted_phone(phone)
parsed_phone = Phonelib.parse(phone)
return phone if parsed_phone.invalid?
formatted =
if parsed_phone.country_code == "1"
parsed_phone.full_national
else
parsed_phone.full_international
end
formatted.gsub!(";", " x")
formatted
end
def test_number(phone)
puts "#" * 20
puts "Checking: " + phone
phone = normalize_phone(phone)
unless phone.length.eql?(12)
puts "Not a valid number !!!"
return
end
puts "Normalised: " + phone
phone = formatted_phone(phone)
puts "Formatted: " + phone
end
test_number "08255555555" # Too many numbers
test_number "082555555" # Too few numbers
test_number "0995555555" # Non valid three digit area code
test_number "0595555555" # Non valid three digit area code
test_number "082-555-5555" # Valid
test_number "0825555555" # Valid
test_number "(082)555-5555" # Valid
test_number "+27 (82)555-5555" # Valid
test_number "27825555555" # Valid
test_number "0027825555555" # Valid
# /bin/zsh -c "bash -c 'env RBENV_VERSION=2.7.2 /usr/local/Cellar/rbenv/1.1.2/libexec/rbenv exec ruby '\"'\"'/Users/davidteren/Library/Application Support/JetBrains/RubyMine2021.1/scratches/scratch_50.rb'\"'\"''"
#
####################
# Checking: 08255555555
# Not a valid number !!!
# ####################
# Checking: 082555555
# Not a valid number !!!
# ####################
# Checking: 0995555555
# Not a valid number !!!
# ####################
# Checking: 0595555555
# Not a valid number !!!
# ####################
# Checking: 082-555-5555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
# ####################
# Checking: 0825555555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
# ####################
# Checking: (082)555-5555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
# ####################
# Checking: +27 (82)555-5555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
# ####################
# Checking: 27825555555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
# ####################
# Checking: 0027825555555
# Normalised: +27825555555
# Formatted: +27 82 555 5555
#
# Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment