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) ⇒ StoreModel::Types::EnumType

Initializes type for mapping

Parameters:

  • mapping (Hash)

    mapping for enum values



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

def initialize(mapping)
  @mapping = mapping
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



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

def cast_value(value)
  return if value.blank?

  case value
  when String, Symbol then cast_symbol_value(value.to_sym)
  when Integer 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)


21
22
23
# File 'lib/store_model/types/enum_type.rb', line 21

def type
  :integer
end