Class: SignalApi::Phone

Inherits:
Object
  • Object
show all
Defined in:
lib/signal_api/util/phone.rb

Class Method Summary collapse

Class Method Details

.format(phone_number, international = false) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/signal_api/util/phone.rb', line 25

def self.format(phone_number, international=false)
  if Phone.valid?(phone_number)
    phone_number = Phone.sanitize(phone_number)
    unless international
      "#{phone_number[0..2]}-#{phone_number[3..5]}-#{phone_number[6..9]}" # 312-343-1326
    else
      phone_number
    end
  end
end

.sanitize(phone_number) ⇒ Object

Clean up phone number by removing special characters and country codes (if provided)



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/signal_api/util/phone.rb', line 5

def self.sanitize(phone_number)
  return nil if phone_number.nil?

  # Remove all non-numeric characters, ex - "=", "+", "(", ")", ".", "a", "A", " "
  sanitized_phone_number = phone_number.gsub(/[^\d]/, '')

  # Remove the US/Canadian country code (+1) if was provided
  if sanitized_phone_number.length > 10 && sanitized_phone_number[0,1] == "1"
    sanitized_phone_number = sanitized_phone_number[1, sanitized_phone_number.size]
  end

  sanitized_phone_number
end

.valid?(phone_number) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
# File 'lib/signal_api/util/phone.rb', line 19

def self.valid?(phone_number)
  return false if phone_number.nil? || phone_number.strip.empty?
  return false if self.sanitize(phone_number).size != 10
  return true
end