Class: Parse::Phone

Inherits:
Object
  • Object
show all
Defined in:
lib/parse/model/phone.rb

Overview

This class provides E.164 phone number validation and formatting for Parse properties. E.164 is the international telephone numbering format that ensures worldwide uniqueness.

Format: +[country code][subscriber number]

  • Must start with +
  • Country code: 1-3 digits (cannot start with 0)
  • Subscriber number: remaining digits
  • Total length: 8-15 digits (including country code)

== Enhanced Validation with phonelib

For comprehensive phone number validation (including carrier validation, number type detection, and accurate country-specific rules), add the phonelib gem to your Gemfile:

gem 'phonelib'

When phonelib is available, Parse::Phone will use Google's libphonenumber data for:

  • Accurate validation for all countries and territories
  • Number type detection (mobile, landline, toll-free, etc.)
  • Carrier information
  • Proper formatting per country standards

Without phonelib, basic E.164 format validation is used (sufficient for most use cases).

Examples:

Basic usage

class Contact < Parse::Object
  property :mobile, :phone
  property :work_phone, :phone, required: true
end

contact = Contact.new
contact.mobile = "+14155551234"
contact.mobile.valid?        # => true
contact.mobile.country_code  # => "1"
contact.mobile.national      # => "4155551234"

contact.mobile = "invalid"
contact.mobile.valid?        # => false

contact.mobile = "+1 (415) 555-1234"  # Automatically cleaned
contact.mobile.to_s          # => "+14155551234"

With phonelib (enhanced features)

phone = Parse::Phone.new("+14155551234")
phone.phone_type    # => :mobile (requires phonelib)
phone.carrier       # => "Verizon" (requires phonelib)
phone.possible?     # => true (quick check, requires phonelib)

Version:

  • 3.0.0

Constant Summary collapse

E164_REGEX =

E.164 format regex (strict validation for fallback mode)

  • Starts with +
  • Country code: 1-3 digits, cannot start with 0
  • Total digits: 8-15 (E.164 max is 15 digits total including country code)
/\A\+[1-9]\d{6,14}\z/
STRIP_NON_DIGITS =

Regex to strip non-digit characters (except +)

/[^\d+]/
NANP_NATIONAL =

A 10-digit North American Numbering Plan number: area code and exchange code each start with 2-9.

/\A[2-9]\d{2}[2-9]\d{6}\z/

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#new(number) ⇒ Parse::Phone #new(phone) ⇒ Parse::Phone

Creates a new Phone instance.

Examples:

Parse::Phone.new("+14155551234")
Parse::Phone.new("1-415-555-1234")  # Will add + prefix
Parse::Phone.new("+1 (415) 555-1234")  # Will clean formatting

Overloads:



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/parse/model/phone.rb', line 131

def initialize(value)
  @raw = nil
  @number = nil
  @phonelib_phone = nil

  if value.is_a?(String)
    @raw = value
    @number = normalize(value)
  elsif value.is_a?(Parse::Phone)
    @raw = value.raw
    @number = value.number
  elsif value.respond_to?(:to_s) && !value.nil?
    @raw = value.to_s
    @number = normalize(@raw)
  end

  # Parse with phonelib if available
  @phonelib_phone = Phonelib.parse(@number) if PHONELIB_AVAILABLE && @number
end

Class Attribute Details

.default_country_code ⇒ String?

Returns see default_country_code=.

Returns:



89
90
91
# File 'lib/parse/model/phone.rb', line 89

def default_country_code
  defined?(@default_country_code) ? @default_country_code : "1"
end

Instance Attribute Details

#number ⇒ String (readonly)

Returns the normalized E.164 formatted number (or nil if invalid input).

Returns:

  • (String) —

    the normalized E.164 formatted number (or nil if invalid input)



116
117
118
# File 'lib/parse/model/phone.rb', line 116

def number
  @number
end

#raw ⇒ String (readonly)

Returns the raw input value.

Returns:

  • (String) —

    the raw input value



113
114
115
# File 'lib/parse/model/phone.rb', line 113

def raw
  @raw
end

Class Method Details

.phonelib_available? ⇒ Boolean

Check if phonelib is available for enhanced validation

Returns:

  • (Boolean) —

    true if phonelib gem is loaded



95
96
97
# File 'lib/parse/model/phone.rb', line 95

def phonelib_available?
  PHONELIB_AVAILABLE
end

.typecast(value) ⇒ Parse::Phone?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Type casting support for Parse properties. This allows the property system to convert values to Phone instances.

Parameters:

  • value (Object) —

    the value to typecast

Returns:



105
106
107
108
109
# File 'lib/parse/model/phone.rb', line 105

def typecast(value)
  return nil if value.nil?
  return value if value.is_a?(Parse::Phone)
  Parse::Phone.new(value)
end

Instance Method Details

#==(other) ⇒ Boolean

Check equality with another phone number.

Parameters:

Returns:

  • (Boolean) —

    true if the numbers are equal



388
389
390
391
392
393
394
395
396
# File 'lib/parse/model/phone.rb', line 388

def ==(other)
  if other.is_a?(Parse::Phone)
    @number == other.number
  elsif other.is_a?(String)
    @number == normalize(other)
  else
    false
  end
end

#as_json(*args) ⇒ String?

Returns the E.164 formatted phone number for JSON serialization.

Returns:

  • (String, nil) —

    the E.164 formatted phone number for JSON serialization



206
207
208
# File 'lib/parse/model/phone.rb', line 206

def as_json(*args)
  @number
end

#blank? ⇒ Boolean

Returns true if the phone number is blank/nil.

Returns:

  • (Boolean) —

    true if the phone number is blank/nil



399
400
401
# File 'lib/parse/model/phone.rb', line 399

def blank?
  @number.blank?
end

#carrier ⇒ String?

Get the carrier name for this phone number. Requires phonelib and may not be available for all numbers.

Returns:

  • (String, nil) —

    the carrier name or nil



326
327
328
329
# File 'lib/parse/model/phone.rb', line 326

def carrier
  return nil unless PHONELIB_AVAILABLE && @phonelib_phone&.valid?
  @phonelib_phone.carrier
end

#country ⇒ String?

Get the two-letter ISO country code. Requires phonelib for accurate detection.

Examples:

Parse::Phone.new("+14155551234").country  # => "US" (with phonelib)

Returns:

  • (String, nil) —

    the ISO 3166-1 alpha-2 country code (e.g., "US", "GB")



276
277
278
279
# File 'lib/parse/model/phone.rb', line 276

def country
  return nil unless PHONELIB_AVAILABLE && @phonelib_phone&.valid?
  @phonelib_phone.country
end

#country_code ⇒ String?

Get the country code portion of the phone number.

Examples:

Parse::Phone.new("+14155551234").country_code  # => "1"
Parse::Phone.new("+442071234567").country_code # => "44"

Returns:

  • (String, nil) —

    the country code (without +) or nil if invalid



259
260
261
262
263
264
265
266
267
# File 'lib/parse/model/phone.rb', line 259

def country_code
  return nil unless valid?

  if PHONELIB_AVAILABLE && @phonelib_phone
    @phonelib_phone.country_code
  else
    extract_country_code_fallback
  end
end

#country_name ⇒ String?

Get the country/region name for this phone number's country code.

Examples:

Parse::Phone.new("+14155551234").country_name  # => "United States"
Parse::Phone.new("+442071234567").country_name # => "United Kingdom"

Returns:

  • (String, nil) —

    the country/region name or nil if unknown



347
348
349
350
351
352
353
354
355
# File 'lib/parse/model/phone.rb', line 347

def country_name
  if PHONELIB_AVAILABLE && @phonelib_phone&.valid?
    iso_code = @phonelib_phone.country
    ISO_COUNTRY_NAMES[iso_code] if iso_code
  else
    cc = country_code
    FALLBACK_COUNTRY_NAMES[cc] if cc
  end
end

#errors ⇒ Array<String>

Get validation errors for this phone number. Useful for providing user feedback.

Returns:



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/parse/model/phone.rb', line 412

def errors
  return [] if valid?
  return ["Phone number is required"] if @number.blank?

  if PHONELIB_AVAILABLE && @phonelib_phone
    result = []
    # Phonelib uses impossible? for basic length/format check
    if @phonelib_phone.impossible?
      sanitized = @phonelib_phone.sanitized
      result << "Phone number is too short" if sanitized.length < 7
      result << "Phone number is too long" if sanitized.length > 15
    end
    result << "Invalid phone number format" if result.empty?
    result
  else
    ["Invalid E.164 phone number format"]
  end
end

#formatted(format = :international) ⇒ String?

Format the phone number for display. When phonelib is available, uses proper country-specific formatting. Otherwise, provides basic formatted version.

Examples:

Parse::Phone.new("+14155551234").formatted             # => "+1 415-555-1234"
Parse::Phone.new("+14155551234").formatted(:national)  # => "(415) 555-1234"

Parameters:

  • format (Symbol) (defaults to: :international) —

    :international (default), :national, or :e164

Returns:

  • (String, nil) —

    formatted number or nil if invalid



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/parse/model/phone.rb', line 367

def formatted(format = :international)
  return nil unless valid?

  if PHONELIB_AVAILABLE && @phonelib_phone
    case format
    when :national
      @phonelib_phone.national
    when :e164
      @phonelib_phone.e164
    else
      @phonelib_phone.international
    end
  else
    format_fallback
  end
end

#geo_name ⇒ String?

Get the geographic area for this phone number. Requires phonelib and may not be available for mobile numbers.

Returns:

  • (String, nil) —

    the geographic area or nil



335
336
337
338
# File 'lib/parse/model/phone.rb', line 335

def geo_name
  return nil unless PHONELIB_AVAILABLE && @phonelib_phone&.valid?
  @phonelib_phone.geo_name
end

#invalid? ⇒ Boolean

Check if the phone number is invalid.

Returns:

  • (Boolean) —

    true if the phone number is definitely invalid



248
249
250
# File 'lib/parse/model/phone.rb', line 248

def invalid?
  !valid?
end

#mobile? ⇒ Boolean?

Check if this is a mobile phone number. Requires phonelib for accurate detection.

Returns:

  • (Boolean, nil) —

    true if mobile, false if not, nil if unknown



316
317
318
319
320
# File 'lib/parse/model/phone.rb', line 316

def mobile?
  type = phone_type
  return nil if type.nil?
  [:mobile, :fixed_or_mobile].include?(type)
end

#national ⇒ String?

Get the national (subscriber) number without country code.

Examples:

Parse::Phone.new("+14155551234").national  # => "4155551234"

Returns:

  • (String, nil) —

    the national number or nil if invalid



287
288
289
290
291
292
293
294
295
296
297
# File 'lib/parse/model/phone.rb', line 287

def national
  return nil unless valid?

  if PHONELIB_AVAILABLE && @phonelib_phone
    @phonelib_phone.national(false)&.gsub(/\D/, "")
  else
    cc = country_code
    return nil unless cc
    @number[(cc.length + 1)..]  # Skip + and country code
  end
end

#normalize(value) ⇒ String?

Normalize a phone number string to E.164 format. Removes all non-digit characters except a leading +.

Input that already starts with + is kept as dialed. Input without a + is resolved as follows, identically with and without phonelib (phonelib parses the normalized result):

  1. A leading 00 (international access prefix) becomes +.
  2. With default_country_code set to "1" (the default), a 10-digit North American number (4155551234, (415) 555-1234) becomes +14155551234, and an 11-digit number starting with 1 gets a +.
  3. Any other number of 11 or more digits that does not start with 0 is assumed to already include its country code.
  4. A shorter national number (or one with a leading trunk 0) gets the default country code, minus the trunk 0, when that code is not "1". With no default country code it is left without a + so it fails validation instead of being read as some other country's code (previously 4155551234 became the Swiss +41 55 551 234).

Parameters:

  • value (String) —

    the phone number string

Returns:

  • (String, nil) —

    the normalized number or nil if invalid



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/parse/model/phone.rb', line 174

def normalize(value)
  return nil if value.blank?

  # Remove all non-digit characters except +
  cleaned = value.to_s.gsub(STRIP_NON_DIGITS, "")
  return cleaned if cleaned.start_with?("+")

  digits = cleaned.delete("+")
  return "+#{digits}" if digits.empty?
  return "+#{digits[2..]}" if digits.start_with?("00")

  default_cc = Parse::Phone.default_country_code.to_s.delete("+").presence
  if default_cc == "1"
    return "+1#{digits}" if NANP_NATIONAL.match?(digits)
    return "+#{digits}" if digits.length == 11 && digits.start_with?("1") && NANP_NATIONAL.match?(digits[1..])
  end

  return "+#{digits}" if digits.length >= 11 && !digits.start_with?("0")

  if default_cc && default_cc != "1"
    "+#{default_cc}#{digits.sub(/\A0/, "")}"
  else
    digits
  end
end

#phone_type ⇒ Symbol?

Get the phone number type (mobile, landline, etc.). Requires phonelib for type detection.

Examples:

Parse::Phone.new("+14155551234").phone_type  # => :mobile (with phonelib)

Returns:

  • (Symbol, nil) —

    the number type (:mobile, :fixed_line, :toll_free, etc.)



306
307
308
309
310
# File 'lib/parse/model/phone.rb', line 306

def phone_type
  return nil unless PHONELIB_AVAILABLE && @phonelib_phone&.valid?
  types = @phonelib_phone.types
  types.first if types.any?
end

#possible? ⇒ Boolean

Check if the phone number is possibly valid (quick check). This is faster than full validation and useful for input feedback. Falls back to valid? when phonelib is not available.

Returns:

  • (Boolean) —

    true if the number could be valid



235
236
237
238
239
240
241
242
243
# File 'lib/parse/model/phone.rb', line 235

def possible?
  return false if @number.blank?

  if PHONELIB_AVAILABLE && @phonelib_phone
    @phonelib_phone.possible?
  else
    valid?
  end
end

#present? ⇒ Boolean

Returns true if the phone number is present.

Returns:

  • (Boolean) —

    true if the phone number is present



404
405
406
# File 'lib/parse/model/phone.rb', line 404

def present?
  !blank?
end

#to_s ⇒ String?

Returns the E.164 formatted phone number.

Returns:

  • (String, nil) —

    the E.164 formatted phone number



201
202
203
# File 'lib/parse/model/phone.rb', line 201

def to_s
  @number
end

#valid? ⇒ Boolean

Check if this phone number is valid E.164 format. When phonelib is available, uses comprehensive validation. Otherwise, uses basic E.164 regex validation.

Examples:

Parse::Phone.new("+14155551234").valid?  # => true
Parse::Phone.new("invalid").valid?       # => false
Parse::Phone.new("+1").valid?            # => false (too short)

Returns:

  • (Boolean) —

    true if the phone number is valid



220
221
222
223
224
225
226
227
228
# File 'lib/parse/model/phone.rb', line 220

def valid?
  return false if @number.blank?

  if PHONELIB_AVAILABLE && @phonelib_phone
    @phonelib_phone.valid?
  else
    E164_REGEX.match?(@number)
  end
end