16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# File 'lib/backframe/activerecord/acts_as_phone.rb', line 16
def acts_as_phone(entity)
class_eval <<-EOV
after_initialize :uncast_phone_#{entity}, :if => Proc.new { |c| !c.new_record? && c.#{entity}.present? }
before_save :cast_phone_#{entity}, :if => Proc.new { |c| c.#{entity}.present? }
after_save :uncast_phone_#{entity}, :if => Proc.new { |c| c.#{entity}.present? }
validate :validates_phone_#{entity}, :if => Proc.new { |c| c.#{entity}.present? }
private
def uncast_phone_#{entity}
self.#{entity} = Phony.format(self.#{entity}, :format => '%{ndc}-%{local}')
end
def cast_phone_#{entity}
self.#{entity} = #{entity}_to_international(self.#{entity})
end
def validates_phone_#{entity}
testvalue = #{entity}_to_international(self.#{entity})
if !Phony.plausible?(testvalue)
self.errors.add(:#{entity}, 'invalid #{entity} number')
end
end
def #{entity}_to_international(value)
regex = Regexp.new('[\\s\\\.\\\-\\\(\\\)]')
newvalue = value.gsub(regex, '')
newvalue = (newvalue.length == 10) ? '1'+value : value
Phony.normalize(newvalue)
end
EOV
end
|