Class: SerializeAttributes::Types::Enum

Inherits:
Object
  • Object
show all
Defined in:
lib/serialize_attributes/types/enum.rb

Overview

A custom type which can only hold one of a set of predetermined values.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(of: [], type: nil) ⇒ Enum

Construct a type instance.

Examples:

Required to be one of two values

attribute :state, :enum, of: ["placed", "confirmed"]

Optionally allowing nil

attribute :folding, :enum, of: [nil, "top-fold", "bottom-fold"]

Casting input/output using another type

attribute :loves_pizza, :enum, of: [true], type: :boolean
# object.loves_pizza = "t"
#=> true

Parameters:

  • of (Array) (defaults to: [])

    One or more possible values that this type can take

  • type (Symbol) (defaults to: nil)

    An optional ActiveModel::Type instance, or symbol, for casting/uncasting (only required if enum has non-primitive types)



27
28
29
30
# File 'lib/serialize_attributes/types/enum.rb', line 27

def initialize(of: [], type: nil)
  @options = of.freeze
  @type    = resolve_type(type)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/serialize_attributes/types/enum.rb', line 9

def options
  @options
end

Instance Method Details

#attach_validations_to(object, field_name) ⇒ Object



32
33
34
# File 'lib/serialize_attributes/types/enum.rb', line 32

def attach_validations_to(object, field_name)
  object.validates_inclusion_of(field_name, in: @options)
end