Class: RichEngine::Enum

Inherits:
Object
  • Object
show all
Defined in:
lib/rich_engine/enum.rb,
lib/rich_engine/enum/mixin.rb,
lib/rich_engine/enum/value.rb

Overview

An ergonomic, comparable enum with query methods. Options may be given as an array (auto-indexed from 0) or as a hash mapping each option to its value. A reader method is defined for every option that returns an Value.

Examples:

Array of options (auto-indexed)

colors = RichEngine::Enum.new(:colors, [:red, :green, :blue])
colors.options #=> {red: 0, green: 1, blue: 2}
colors.red.value #=> 0

Hash of options with explicit values

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

Defined Under Namespace

Modules: Mixin Classes: Value

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options) ⇒ Enum

Builds an enum and defines a reader method for each option.

Parameters:

  • name (Symbol)

    the name of the enum

  • options (Array, Hash)

    option names; an array is auto-indexed from 0, a hash maps each option name to its value



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rich_engine/enum.rb', line 27

def initialize(name, options)
  @name = name
  @options = if options.respond_to? :each_pair
    options
  else
    options.map.with_index.to_h
  end

  @options.each_pair do |option, _value|
    define_singleton_method(option) do
      Enum::Value.new(enum: self, selected: option)
    end
  end

  freeze
end

Instance Attribute Details

#nameSymbol, Hash (readonly)

Returns:

  • (Symbol)

    the name of the enum

  • (Hash)

    the options as a hash mapping each option to its value



20
21
22
# File 'lib/rich_engine/enum.rb', line 20

def name
  @name
end

#optionsSymbol, Hash (readonly)

Returns:

  • (Symbol)

    the name of the enum

  • (Hash)

    the options as a hash mapping each option to its value



20
21
22
# File 'lib/rich_engine/enum.rb', line 20

def options
  @options
end

Instance Method Details

#[](option) ⇒ Object

Looks up the value of an option.

Parameters:

  • option (Symbol)

    the option name

Returns:

  • (Object)

    the value mapped to that option

Raises:

  • (KeyError)

    if the option is unknown



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

def [](option)
  @options.fetch(option)
end