Skip to content

Instantly share code, notes, and snippets.

@marcosinger
Created January 11, 2012 20:43
Show Gist options
  • Save marcosinger/1596661 to your computer and use it in GitHub Desktop.
Save marcosinger/1596661 to your computer and use it in GitHub Desktop.
# encoding: utf-8
module Iceleres
class PhoneNumber
include EnumerateIt
include ActiveModel::Validations
ATTRIBUTES = [:area_code, :number, :type, :validation]
PHONE_FORMAT = /^[1-9]\d{3}[-\s]?\d{4}/
attr_accessor *ATTRIBUTES
class Type < EnumerateIt::Base
associate_values(
:mobile => 1,
:work => 2,
:home => 3
)
end
has_enumeration_for :type, :with => Type, :create_helpers => true
validate :validate_number_and_area_code, :if => lambda { self.validation }
validate :validate_format
def initialize(attributes)
attributes.assert_valid_keys ATTRIBUTES
attributes.each { |key, val| self.send("#{key}=", val) }
end
def formatted
area_code_str = area_code.present? ? "(#{area_code})" : nil
[area_code_str, number].compact.join " "
end
def validate_format
phone_fields = [:area_code, :number]
phone_fields.map do |field|
unless field.blank?
errors.add(field, :invalid) unless field =~ PHONE_FORMAT
end
end
end
def validate_number_and_area_code
phone_fields = [area_code, number]
if [phone_fields].all? { |fields| fields.any? &:blank? }
name = Iceleres::PhoneNumber::Type.t(self.type).downcase
errors.add :base, :no_phone_number_or_area_code
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment