Class: Dialy::Number

Inherits:
Object
  • Object
show all
Defined in:
lib/dialy/formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Number

Returns a new instance of Number.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/dialy/formatter.rb', line 7

def initialize(value)
  raise ArgumentError unless value.is_a?(String)
  
  # Remove all but digits and +
  @number = value.gsub(/[^+0-9]/, '')

  # Plus (+) is only allowed as first character
  raise WrongFormatting if @number.count('+') > 1
  raise WrongFormatting if @number.index('+').to_i > 0

  # Main work
  @country_code = extract_country_code! || Config[:default_country_code]
  @area_code = extract_area_code!
end

Instance Method Details

#to_s(format = :international) ⇒ Object

String representation in E.123 format



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dialy/formatter.rb', line 23

def to_s(format=:international)
  case format
    when :international
      "+#{@country_code} #{[ @area_code, @number ].compact.join(' ')}"
    when :short
      if @country_code == Config[:default_country_code]
        "(0#{@area_code}) #{@number}"
      else
        to_s(:international)
      end
    else
      raise ArgumentError
  end
end