Class: Enummer::EnummerType

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

Instance Method Summary collapse

Constructor Details

#initialize(values:) ⇒ EnummerType

Returns a new instance of EnummerType.

Parameters:

  • values (Array<Symbol>)

    hash with bit-value pairs for all possible values for this type



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

def initialize(values:)
  @values = values
end

Instance Method Details

#cast(value) ⇒ Array<Symbol>

Returns Current value represented as symbols.

Parameters:

  • value (Array<Symbol>)

    Current value represented as one or more symbols or strings

Returns:

  • (Array<Symbol>)

    Current value represented as symbols



42
43
44
# File 'lib/enummer/enummer_type.rb', line 42

def cast(value)
  Array.wrap(value).map(&:to_sym)
end

#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



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

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

  @values.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



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

def serialize(value)
  return unless value

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

#typeObject

Returns Symbol Representation of this type.

Examples:

:enummer[read|write|execute]

Returns:

  • Symbol Representation of this type



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

def type
  :"enummer[#{@values.keys.join("|")}]"
end