Class: PicoPhone::Rails::Type

Inherits:
ActiveModel::Type::Value
  • Object
show all
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.

Examples:

attribute :phone, :phone_number, region: "US"

contact.phone       # => #<PicoPhone::PhoneNumber ...>
contact.phone.e164  # => "+15102745656"

Instance Method Summary collapse

Constructor Details

#initialize(region: nil) ⇒ Type

Returns a new instance of Type.

Parameters:

  • region (String, nil) (defaults to: nil)

    ISO 3166-1 alpha-2 default region used to interpret national-format input



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.

Parameters:

  • value (String, PicoPhone::PhoneNumber, nil)

Returns:

  • (PicoPhone::PhoneNumber, nil)

    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?

Parameters:

  • value (String, nil)

    raw value read from the database

Returns:

  • (PicoPhone::PhoneNumber, nil)


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.

Parameters:

  • value (String, PicoPhone::PhoneNumber, nil)

Returns:

  • (String, nil)

    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

#typeSymbol

Returns always :string -- the underlying column stores a plain string.

Returns:

  • (Symbol)

    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