Class: StoreModel::Types::EnumType

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/store_model/types/enum_type.rb

Overview

Implements ActiveModel::Type::Value type for handling Rails-like enums

Instance Method Summary collapse

Constructor Details

#initialize(mapping, raise_on_invalid_values) ⇒ StoreModel::Types::EnumType

Initializes type for mapping

Parameters:

  • mapping (Hash)

    mapping for enum values



14
15
16
17
18
# File 'lib/store_model/types/enum_type.rb', line 14

def initialize(mapping, raise_on_invalid_values)
  @mapping = mapping
  @raise_on_invalid_values = raise_on_invalid_values
  super()
end

Instance Method Details

#cast_value(value) ⇒ Object

Casts value from DB or user to StoreModel::Model instance

Parameters:

  • value (Object)

    a value to cast

Returns:

  • StoreModel::Model



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/store_model/types/enum_type.rb', line 32

def cast_value(value)
  return if value.blank?

  case value
  when String, Symbol then cast_symbol_value(value)
  when Integer, Float then cast_integer_value(value)
  else
    raise StoreModel::Types::CastError,
          "failed casting #{value.inspect}, only String, Symbol or " \
          "Integer instances are allowed"
  end
end

#typeSymbol

Returns type

Returns:

  • (Symbol)


23
24
25
# File 'lib/store_model/types/enum_type.rb', line 23

def type
  :integer
end