Class: Telein::Util::Phone

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

Overview

Class that encapsulates phone data logic

Constant Summary collapse

FORMAT =

General format of a Brazilian phone. An area_code and a number that may contain and extra 9

/\A\(?(?<area_code>[1-9][0-9])\)?\s*(?<number>(?<extra_digit>9?)[2-9]\d{3}\-?\d{4})\Z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Phone

Returns a new instance of Phone.

Parameters:

  • value (String)

    a string containing phone information



18
19
20
# File 'lib/telein/util/phone.rb', line 18

def initialize(value)
  @matching = value.match(FORMAT) if value
end

Instance Attribute Details

#matchingMatchData (readonly)

The Matching parts of Phone::FORMAT

Returns:

  • (MatchData)

    A +MatchData+ object containing the matching made against value

See Also:



11
12
13
# File 'lib/telein/util/phone.rb', line 11

def matching
  @matching
end

Instance Method Details

#area_codeString

Returns the area code for phone

Returns:

  • (String)

    the area code of phone



37
38
39
# File 'lib/telein/util/phone.rb', line 37

def area_code
  self.matching[:area_code] if self.matching
end

#has_extra_digit?Boolean

Checks if phone has an extra digit The extra digit '9' was introduced only to phones in 11 area code (São Paulo) to account for new phones

Returns:

  • (Boolean)

    whether phone has an extra 9



53
54
55
56
# File 'lib/telein/util/phone.rb', line 53

def has_extra_digit?
  return false unless self.matching
  self.matching[:extra_digit] == '9' ? true : false
end

#numberString

Returns the number part of phone (everything minus area code)

Returns:

  • (String)

    the number part of phone



44
45
46
# File 'lib/telein/util/phone.rb', line 44

def number
  self.matching[:number].delete('-') if self.matching
end

#to_telein_sString

Returns a string ready to be consumed by Telein API

Examples:

Return a formatted phone

phone = Telein::Util::Phone.new('(12) 3434-5656')
phone.to_telein_s # => '1234345656'

Returns:

  • (String)

    a string in Telein format



28
29
30
31
32
# File 'lib/telein/util/phone.rb', line 28

def to_telein_s
  return nil.to_s unless self.valid?

  [self.area_code,self.number].join
end

#valid?Boolean

Checks if phone is valid This is a loosen check, in the sense that it accepts a wide range of probably invalid phones, like (99) 9999-9999 but the specs for area codes in Brazil are also loosen, allowing the existence of such numbers in the future. Also, for phones in the 11 area, the method may return false positives, since only cellphones have that extra digit.

Returns:

  • (Boolean)

    whether phone is valid or invalid



67
68
69
70
71
72
73
# File 'lib/telein/util/phone.rb', line 67

def valid?
  if self.area_code && self.number
    true
  else
    false
  end
end