Class: Ardm::Property::Enum

Inherits:
Object show all
Includes:
Flags
Defined in:
lib/ardm/property/enum.rb

Constant Summary

Constants inherited from Ardm::Property

INVALID_NAMES, Infinity, JSON, OPTIONS, PRIMITIVES, VISIBILITY_OPTIONS

Instance Attribute Summary

Attributes inherited from Ardm::Property

#allow_blank, #allow_nil, #coercion_method, #default, #dump_as, #index, #instance_variable_name, #load_as, #model, #name, #options, #reader_visibility, #required, #unique_index, #writer_visibility

Instance Method Summary collapse

Methods included from Flags

#custom?

Methods inherited from Object

#marshal, #to_child_key, #unmarshal

Methods inherited from Ardm::Property

accept_options, accepted_options, #allow_blank?, #allow_nil?, #assert_valid_value, #bind, demodulize, demodulized_names, descendants, determine_class, #field, find_class, #get, #get!, inherited, #inspect, #key?, #lazy?, #loaded?, options, primitive, #primitive, #primitive?, #properties, #required?, #serial?, #set, #set!, #set_default_value, #unique?, #valid?, #value_dumped?, #value_loaded?

Methods included from Equalizer

#equalize

Methods included from Subject

#default?, #default_for

Methods included from Assertions

#assert_kind_of

Constructor Details

#initialize(model, name, options = {}) ⇒ Enum

Returns a new instance of Enum.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ardm/property/enum.rb', line 12

def initialize(model, name, options = {})
  @flag_map = {}

  flags = options.fetch(:flags, self.class.flags)
  flags.each_with_index do |flag, i|
    @flag_map[i + 1] = flag
  end

  if self.class.accepted_options.include?(:set) && !options.include?(:set)
    options[:set] = @flag_map.values_at(*@flag_map.keys.sort)
  end

  super
end

Instance Method Details

#dump(value) ⇒ Object



31
32
33
34
35
36
# File 'lib/ardm/property/enum.rb', line 31

def dump(value)
  case value
  when ::Array then value.collect { |v| dump(v) }
  else              flag_map.invert[typecast(value)]
  end
end

#load(value) ⇒ Object



27
28
29
# File 'lib/ardm/property/enum.rb', line 27

def load(value)
  flag_map[value.to_i]
end

#typecast(value) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/ardm/property/enum.rb', line 38

def typecast(value)
  return if value.nil?
  # Attempt to typecast using the class of the first item in the map.
  case flag_map[1]
  when ::Symbol then value.to_sym
  when ::String then value.to_s
  when ::Fixnum then value.to_i
  else               value
  end
end