Module: BigPhoney::Rails::ActiveRecord

Defined in:
lib/big_phoney/rails.rb

Instance Method Summary collapse

Instance Method Details

#phone_number_fields(*fields) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/big_phoney/rails.rb', line 4

def phone_number_fields(*fields)
  fields.each do |field|
    define_method("#{field}=") do |value|
      return true if value.blank?
      just_digits = value.to_s.gsub(/[^\d]/, "")
      self[field] = (just_digits.starts_with?("1") ? just_digits[1..-1] : just_digits)
    end
  end
end

#validate_phone(*args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/big_phoney/rails.rb', line 14

def validate_phone(*args)
  args.each do |attribute|
    validate do |record|
      number = record.send(attribute)

      if number and not [1].include?(BigPhoney::PhoneNumber.new(number).country_code.to_i)
        record.errors[attribute] << "must be a valid US phone number"
      end

      if number and not BigPhoney::PhoneNumber.new(number).valid?
        if record.errors[attribute].empty?
          record.errors[attribute] << "is not valid"
        end
      end
    end
  end
end