Class: Enumerize::ActiveModelAttributesSupport::Type

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/enumerize/activemodel.rb

Instance Method Summary collapse

Constructor Details

#initialize(attr) ⇒ Type

Returns a new instance of Type.



33
34
35
# File 'lib/enumerize/activemodel.rb', line 33

def initialize(attr)
  @attr = attr
end

Instance Method Details

#cast(value) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/enumerize/activemodel.rb', line 54

def cast(value)
  case value
  when nil
    return super
  when Array
    if @attr.arguments[:multiple]
      found = @attr.find_values(*value)
      return found.presence || super
    end
  end

  @attr.find_value(value) || value
end

#deserialize(value) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/enumerize/activemodel.rb', line 42

def deserialize(value)
  return nil if value.nil?

  # Use find_values for arrays on multiple: true attributes
  # Otherwise use find_value for single values
  if value.is_a?(Array) && @attr.arguments[:multiple]
    @attr.find_values(*value)
  else
    @attr.find_value(value)
  end
end

#serialize(value) ⇒ Object



37
38
39
40
# File 'lib/enumerize/activemodel.rb', line 37

def serialize(value)
  v = @attr.find_value(value)
  v && v.value
end

#typeObject



29
30
31
# File 'lib/enumerize/activemodel.rb', line 29

def type
  :enumerize
end