Class: Predicates::PhoneNumber

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

Overview

Defines a field as a phone number. Currently it assumes the phone number fits the North American Numbering Plan. Future support of other plans will be implemented by calling code, e.g. 44 (UK) or 33 (FR). These will act as triggers for localized phone number validation.

Options

  • implied_country_code [integer, default: 1 (North America)]

Example

field_is_a_phone_number

Defined Under Namespace

Classes: Patterns

Instance Attribute Summary collapse

Attributes inherited from Base

#full_message, #or_empty, #validate_if, #validate_on

Instance Method Summary collapse

Methods inherited from Base

#allow_empty?, #error, #error_binds

Constructor Details

#initialize(attr, options = {}) ⇒ PhoneNumber

Returns a new instance of PhoneNumber.



11
12
13
14
# File 'lib/predicates/phone_number.rb', line 11

def initialize(attr, options = {})
  options[:implied_country_code] ||= 1
  super(attr, options)
end

Instance Attribute Details

#implied_country_codeObject

Returns the value of attribute implied_country_code.



9
10
11
# File 'lib/predicates/phone_number.rb', line 9

def implied_country_code
  @implied_country_code
end

Instance Method Details

#error_messageObject



16
17
18
# File 'lib/predicates/phone_number.rb', line 16

def error_message
  @error_message ||= :phone
end

#normalize(value) ⇒ Object

strip out all non-numeric characters except a leading +



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/predicates/phone_number.rb', line 47

def normalize(value)
  return value if value.blank?

  value = "+#{value}" if value.to_s[0..0] == '1' # north american bias
  value = "+#{implied_country_code}#{value}" unless value.to_s[0..0] == '+'

  leading_plus = (value[0..0] == '+')
  value.gsub!(/[^0-9]/, '')
  value = "+#{value}" if leading_plus
  value
end

#to_human(value) ⇒ Object

check country code, then format differently for each country



35
36
37
38
39
40
41
42
43
44
# File 'lib/predicates/phone_number.rb', line 35

def to_human(value)
  case value
    when Patterns::NANP
    m = $~
    "(#{m[1]}) #{m[2]}-#{m[3]}"

    else
    value
  end
end

#validate(value, record) ⇒ Object



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

def validate(value, record)
  case value
    when Patterns::NANP
    match = $~
    valid = !match.nil?
    valid &&= (match[2] != '555' or match[3][0..1] != '01') # 555-01xx are reserved (http://en.wikipedia.org/wiki/555_telephone_number)

    else
    valid = false
  end

  valid
end