Class: PicoPhone::Rails::Type
- Inherits:
-
ActiveModel::Type::Value
- Object
- ActiveModel::Type::Value
- PicoPhone::Rails::Type
- Defined in:
- lib/pico_phone/rails/type.rb
Overview
Registered as :phone_number in the railtie. Casts a stored string to a
PicoPhone::PhoneNumber on read and serializes back to E.164 on write.
Instance Method Summary collapse
-
#cast(value) ⇒ PicoPhone::PhoneNumber?
nilfornilinput; never raises on unparseable input. - #deserialize(value) ⇒ PicoPhone::PhoneNumber?
-
#initialize(region: nil) ⇒ Type
constructor
A new instance of Type.
-
#serialize(value) ⇒ String?
E.164 for a valid number, the original string for an invalid one,
nilfornilinput. -
#type ⇒ Symbol
Always
:string-- the underlying column stores a plain string.
Constructor Details
#initialize(region: nil) ⇒ Type
Returns a new instance of Type.
17 18 19 20 |
# File 'lib/pico_phone/rails/type.rb', line 17 def initialize(region: nil) @region = region super() end |
Instance Method Details
#cast(value) ⇒ PicoPhone::PhoneNumber?
Returns nil for nil input; never raises on unparseable input.
29 30 31 32 33 34 |
# File 'lib/pico_phone/rails/type.rb', line 29 def cast(value) return value if value.is_a?(PicoPhone::PhoneNumber) return nil if value.nil? PicoPhone.parse(value.to_s, @region) end |
#deserialize(value) ⇒ PicoPhone::PhoneNumber?
47 48 49 |
# File 'lib/pico_phone/rails/type.rb', line 47 def deserialize(value) cast(value) end |
#serialize(value) ⇒ String?
Returns E.164 for a valid number, the original string for an invalid one, nil for nil input.
38 39 40 41 42 43 |
# File 'lib/pico_phone/rails/type.rb', line 38 def serialize(value) return nil if value.nil? phone_number = value.is_a?(PicoPhone::PhoneNumber) ? value : PicoPhone.parse(value.to_s, @region) phone_number.valid? ? phone_number.e164 : phone_number.to_s end |
#type ⇒ Symbol
Returns always :string -- the underlying column stores a plain string.
23 24 25 |
# File 'lib/pico_phone/rails/type.rb', line 23 def type :string end |