Class: Ardm::Property::Flag

Inherits:
Object show all
Includes:
Flags
Defined in:
lib/ardm/property/flag.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 = {}) ⇒ Flag

Returns a new instance of Flag.



12
13
14
15
16
17
18
19
20
21
# File 'lib/ardm/property/flag.rb', line 12

def initialize(model, name, options = {})
  super

  @flag_map = {}

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

Instance Method Details

#dump(value) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ardm/property/flag.rb', line 39

def dump(value)
  unless value.nil?
    flags = Array(value).map { |flag| flag.to_sym }
    flags.uniq!

    flag = 0

    flag_map.invert.values_at(*flags).each do |i|
      next if i.nil?
      flag += (1 << i)
    end

    flag
  end
end

#load(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ardm/property/flag.rb', line 23

def load(value)
  return [] if value.nil? || value <= 0

  begin
    matches = []

    0.upto(flag_map.size - 1) do |i|
      matches << flag_map[i] if value[i] == 1
    end

    matches.compact
  rescue TypeError, Errno::EDOM
    []
  end
end

#typecast(value) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/ardm/property/flag.rb', line 55

def typecast(value)
  case value
    when nil     then nil
    when ::Array then value.map { |v| v.to_sym }
    else [value.to_sym]
  end
end