Class: Mongoid::Enum::EnumType

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/enum/enum_type.rb

Overview

Internal: Mapping wrapper used as type for enum fields.

Handles label-value conversion.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mappings) ⇒ EnumType

Returns a new instance of EnumType.



9
10
11
# File 'lib/mongoid/enum/enum_type.rb', line 9

def initialize(mappings)
  @mappings = mappings
end

Instance Attribute Details

#mappingsObject (readonly)

:nodoc:



7
8
9
# File 'lib/mongoid/enum/enum_type.rb', line 7

def mappings
  @mappings
end

Instance Method Details

#demongoize(value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mongoid/enum/enum_type.rb', line 29

def demongoize(value)
  if mappings.value? value
    key = mappings.key value
  elsif value.blank?
    key = nil
  elsif value.is_a? Enum::InvalidKey
    key = value.original_key
  else
    key = Enum::InvalidValue.new(value)
  end
  key
end

#mongoize(key) ⇒ Object Also known as: evolve



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/mongoid/enum/enum_type.rb', line 13

def mongoize(key)
  if key.blank?
    value = nil
  elsif mappings.key? key
    value = mappings[key]
  elsif mappings.value? key
    # XXX Mongoid may try to mongoize multiple times so if key is a valid value
    # assume that it has already been converted to value.
    value = key
  else
    value = Enum::InvalidKey.new(key)
  end
  value
end