Class: RichEngine::Enum::Value

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/rich_engine/enum/value.rb

Overview

A single selected option of an RichEngine::Enum. Values are comparable (by their underlying option value) and expose a query method per option, e.g. +#idle?+. Only values from the same enum can be compared or are equal.

Examples:

state = RichEngine::Enum.new(:state, {idle: 0, running: 1})
value = state.running
value.running? #=> true
value.value    #=> 1

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enum:, selected:) ⇒ Value

Builds a value for a selected option and defines a query method per option (e.g. +#idle?+).

Parameters:

  • enum (Enum)

    the enum this value belongs to

  • selected (Symbol)

    the selected option; must be a valid option of +enum+

Raises:

  • (ArgumentError)

    if +selected+ is not an option of +enum+



26
27
28
29
30
31
32
33
34
# File 'lib/rich_engine/enum/value.rb', line 26

def initialize(enum:, selected:)
  @enum = enum
  @selected = selected

  check_selected_is_a_valid_option
  define_query_methods

  freeze
end

Instance Attribute Details

#enumEnum, Symbol (readonly)

Returns:

  • (Enum)

    the enum this value belongs to

  • (Symbol)

    the selected option



17
18
19
# File 'lib/rich_engine/enum/value.rb', line 17

def enum
  @enum
end

#selectedEnum, Symbol (readonly)

Returns:

  • (Enum)

    the enum this value belongs to

  • (Symbol)

    the selected option



17
18
19
# File 'lib/rich_engine/enum/value.rb', line 17

def selected
  @selected
end

Instance Method Details

#<=>(other) ⇒ Integer

Compares two values from the same enum by their underlying values.

Parameters:

  • other (Value)

    another value from the same enum

Returns:

  • (Integer)

    -1, 0, or 1

Raises:

  • (ArgumentError)

    if +other+ belongs to a different enum



48
49
50
51
52
# File 'lib/rich_engine/enum/value.rb', line 48

def <=>(other)
  raise ArgumentError, "Can't compare values from different enums" if enum != other.enum

  value <=> other.value
end

#==(other) ⇒ Boolean

Two values are equal when they come from the same enum and have the same selected option.

Parameters:

  • other (Object)

    the object to compare against

Returns:

  • (Boolean)

    whether the values are equal



59
60
61
62
63
# File 'lib/rich_engine/enum/value.rb', line 59

def ==(other)
  return @enum == other.enum && selected == other.selected if other.is_a? self.class

  super
end

#valueObject

The underlying value of the selected option.

Returns:

  • (Object)

    the value mapped to the selected option



39
40
41
# File 'lib/rich_engine/enum/value.rb', line 39

def value
  @enum[@selected]
end