Class: PeoplePlacesThings::PhoneNumber

Inherits:
Object
  • Object
show all
Defined in:
lib/people_places_things/phone_number.rb

Constant Summary

OUTPUT_FORMATS =
[:full_digits, :local_digits, :full_formatted, :local_formatted]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ PhoneNumber



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/people_places_things/phone_number.rb', line 5

def initialize(str)
  self.raw = str
  extract = str.strip.match(/^([-+()\d ]+)$/)[0].gsub(/[^\d]/, '') rescue nil
  raise "Unsupported Format" if !extract || extract.length < 10 || extract.length > 11

  if extract.length == 11
    self.country_code = extract.slice!(0..0)
  else
    self.country_code = '1'
  end

  raise "Unsupported Format" if self.country_code != '1'

  self.area_code = extract.slice!(0..2)

  self.number = extract.dup

  self.exchange = extract.slice!(0..2)

  self.suffix = extract

  raise "Unsupported Format" if !self.exchange || !self.suffix
end

Instance Attribute Details

#area_codeObject

Returns the value of attribute area_code



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def area_code
  @area_code
end

#country_codeObject

Returns the value of attribute country_code



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def country_code
  @country_code
end

#exchangeObject

Returns the value of attribute exchange



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def exchange
  @exchange
end

#numberObject

Returns the value of attribute number



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def number
  @number
end

#rawObject

Returns the value of attribute raw



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def raw
  @raw
end

#suffixObject

Returns the value of attribute suffix



3
4
5
# File 'lib/people_places_things/phone_number.rb', line 3

def suffix
  @suffix
end

Instance Method Details

#to_s(fmt = :full_formatted) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/people_places_things/phone_number.rb', line 29

def to_s(fmt = :full_formatted)
  raise "Unsupported Format" if !OUTPUT_FORMATS.include?(fmt)

  case fmt
    when :full_digits
      "#{self.country_code}#{self.area_code}#{self.exchange}#{self.suffix}"
    
    when :local_digits
      "#{self.exchange}#{self.suffix}"
    
    when :full_formatted
      "#{self.country_code} (#{self.area_code}) #{self.exchange}-#{self.suffix}"
    
    when :local_formatted
      "#{self.exchange}-#{self.suffix}"
  end
end