Module: E164

Defined in:
lib/e164.rb

Constant Summary collapse

ValidFormat =
/^\+([\d]{1,3})([\d]{1,14})$/
Identifiers =
['+','011', '00']
DefaultIdentifier =
'+'
DefaultCountryCode =

Override by E164.set_default_country_code!()

'1'
DefaultCountryLength =

Override by E164.set_default_country_length!()

10

Class Method Summary collapse

Class Method Details

.country_codesObject



11
12
13
# File 'lib/e164.rb', line 11

def self.country_codes
  CountryCodes
end

.e164_clean(num) ⇒ Object



34
35
36
# File 'lib/e164.rb', line 34

def self.e164_clean(num)
  num.scan(/^(?:#{Identifiers.map{|i| Regexp.escape(i) }.join('|')})|[\d]/)
end

.join_country_code(num) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/e164.rb', line 38

def self.join_country_code(num)
  potentials = (1..3).map {|l| num[0,l].join}
  country_code = potentials.map {|x| CountryCodes[x] ? x : nil}.compact.first

  unless country_code
    country_code = DefaultCountryCode
    num.unshift(country_code)
  end

  [num.shift(country_code.length).join, *num]
end

.join_national_destination_code(num) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/e164.rb', line 50

def self.join_national_destination_code(num)
  country = CountryCodes[num[0]]

  case (destination_codes = country[:national_destination_codes])
  when Integer
    destination_code_length = destination_codes
  when Hash
    potentials = destination_codes[:range].map {|l| num[1,l].join}
    destination_code = potentials.map {|x| destination_codes[x] ? x : nil}.compact.first
    destination_code_length = (destination_code && destination_code.length) || destination_codes[:default]
  end

  [num.shift, num.shift(destination_code_length).join, *num]
end

.normalize(num) ⇒ Object



15
16
17
# File 'lib/e164.rb', line 15

def self.normalize(num)
  parse(num).unshift(DefaultIdentifier).join
end

.parse(num) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/e164.rb', line 19

def self.parse(num)
  num = e164_clean(num)
  identifier = Identifiers.include?(num.first) ? num.shift : nil

  if identifier || num.join.start_with?(DefaultCountryCode)
    num = join_country_code(num)
  else
    num = num.unshift(DefaultCountryCode) if num.join.length == DefaultCountryLength
  end

  num = join_national_destination_code(num) if CountryCodes[num[0]]

  [num.shift,num.shift,num.join]
end

.set_default_country_code!(country_code) ⇒ Object



65
66
67
68
69
# File 'lib/e164.rb', line 65

def self.set_default_country_code!(country_code)
  ret_value = remove_const(:DefaultCountryCode)
  const_set(:DefaultCountryCode, country_code)
  ret_value
end

.set_default_country_length!(country_length) ⇒ Object



71
72
73
74
75
# File 'lib/e164.rb', line 71

def self.set_default_country_length!(country_length)
  ret_value = remove_const(:DefaultCountryLength)
  const_set(:DefaultCountryLength, country_length)
  ret_value
end