Class: Twilio::Rails::PhoneNumberFormatter::NorthAmerica
- Inherits:
-
Object
- Object
- Twilio::Rails::PhoneNumberFormatter::NorthAmerica
- Defined in:
- lib/twilio/rails/phone_number_formatter/north_america.rb
Overview
Formats phone numbers as North American 10 digit numbers only, and treats any other number as invalid. This is the legacy behavior from 1.0 which will be the default still in 1.1 as an upgrade path.
Constant Summary collapse
- PHONE_NUMBER_REGEX =
/\A\+1[0-9]{10}\Z/
- PHONE_NUMBER_SEGMENTS_REGEX =
/\A\+1([0-9]{3})([0-9]{3})([0-9]{4})\Z/
Instance Method Summary collapse
- #coerce(string) ⇒ Object
- #display(string) ⇒ Object
- #to_param(string) ⇒ Object
- #valid?(string) ⇒ Boolean
Instance Method Details
#coerce(string) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/twilio/rails/phone_number_formatter/north_america.rb', line 12 def coerce(string) string = string.number if string.is_a?(Twilio::Rails::PhoneNumber) string = string.to_s.presence if string string = string.gsub(/[^0-9]/, "") string = "1#{string}" unless string.starts_with?("1") string = "+#{string}" string = nil unless valid?(string) end string end |
#display(string) ⇒ Object
39 40 41 42 43 44 45 46 47 48 |
# File 'lib/twilio/rails/phone_number_formatter/north_america.rb', line 39 def display(string) coerced_phone_number = coerce(string) if coerced_phone_number matches = coerced_phone_number.match(PHONE_NUMBER_SEGMENTS_REGEX) raise Twilio::Rails::Error, "[display] Phone number marked as valid but could not capture. I made a bad regex: #{string}" unless matches "(#{matches.captures[0]}) #{matches.captures[1]} #{matches.captures[2]}" else string end end |
#to_param(string) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/twilio/rails/phone_number_formatter/north_america.rb', line 31 def to_param(string) string = coerce(string) return "" unless string matches = string.match(PHONE_NUMBER_SEGMENTS_REGEX) raise Twilio::Rails::Error, "[to_param] Phone number marked as valid but could not capture. I made a bad regex: #{string}" unless matches matches.captures.join("-") end |
#valid?(string) ⇒ Boolean
26 27 28 29 |
# File 'lib/twilio/rails/phone_number_formatter/north_america.rb', line 26 def valid?(string) string = string.number if string.is_a?(Twilio::Rails::PhoneNumber) !!string&.match?(PHONE_NUMBER_REGEX) end |