Class: Enummer::EnummerType

Inherits:
ActiveRecord::Type::Value
  • Object
show all
Defined in:
lib/enummer/enummer_type.rb

Instance Method Summary collapse

Constructor Details

#initialize(value_names:) ⇒ EnummerType

Returns a new instance of EnummerType.

Parameters:

  • value_names (Array<Symbol>)

    list of all possible values for this type



8
9
10
11
# File 'lib/enummer/enummer_type.rb', line 8

def initialize(value_names:)
  @value_names = value_names
  @bit_pairs = determine_bit_pairs(value_names)
end

Instance Method Details

#deserialize(value) ⇒ Array<Symbol>

Returns Current value represented as symbols.

Parameters:

  • value (Numeric)

    Numeric representation of values

Returns:

  • (Array<Symbol>)

    Current value represented as symbols



30
31
32
33
34
35
36
37
38
39
# File 'lib/enummer/enummer_type.rb', line 30

def deserialize(value)
  return [] unless value
  return [] if value.to_i.zero?

  @bit_pairs.each_with_object([]) do |(pair_name, pair_value), value_names|
    next if (value & pair_value).zero?

    value_names << pair_name
  end
end

#serialize(value) ⇒ Object

Returns Numeric Numeric representation of values.

Parameters:

  • value (Symbol|Array<Symbol>)

    Current value represented as one or more symbols

Returns:

  • Numeric Numeric representation of values



22
23
24
25
26
# File 'lib/enummer/enummer_type.rb', line 22

def serialize(value)
  return unless value

  Array.wrap(value).sum { |value_name| @bit_pairs.fetch(value_name.to_sym, 0) }
end

#typeObject

Returns Symbol Representation of this type.

Examples:

:enummer[read|write|execute]

Returns:

  • Symbol Representation of this type



16
17
18
# File 'lib/enummer/enummer_type.rb', line 16

def type
  "enummer[#{@value_names.join("|")}]".to_sym
end