Class: Ronin::Core::Params::Types::Enum

Inherits:
Type
  • Object
show all
Defined in:
lib/ronin/core/params/types/enum.rb

Overview

Represents a mapping of Ruby values to their String equivalents.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values) ⇒ Enum

Initializes the enum type.

Parameters:

  • values (Array<Object>)

    The values of the enum type.

Raises:

  • (ArgumentError)

    Cannot initialize an enum type with an empty Array of values.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ronin/core/params/types/enum.rb', line 48

def initialize(values)
  if values.empty?
    raise(ArgumentError,"cannot initialize an empty Enum")
  end

  @values = values
  @map    = {}

  values.each do |value|
    @map[value.to_s] = value
  end
end

Instance Attribute Details

#valuesArray<Object> (readonly)

The values of the enum.

Returns:

  • (Array<Object>)


35
36
37
# File 'lib/ronin/core/params/types/enum.rb', line 35

def values
  @values
end

Class Method Details

.[](*values) ⇒ Enum

Creates a new enum.

Parameters:

  • values (Array<Object>)

    List of enum values.

Returns:

  • (Enum)

    The newly created enum object.



72
73
74
# File 'lib/ronin/core/params/types/enum.rb', line 72

def self.[](*values)
  new(values)
end

Instance Method Details

#coerce(value) ⇒ Symbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Coerces the value into one of the enum values.

Parameters:

  • value (::String, ::Symbol, Object)

Returns:

  • (Symbol)

    The coerced value.

Raises:

  • (ValidationError)

    The value was not a valid enum value or a String that maps to an enum value.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/ronin/core/params/types/enum.rb', line 90

def coerce(value)
  case value
  when ::Symbol
    unless @values.include?(value)
      raise(ValidationError,"unknown value (#{value.inspect})")
    end

    value
  when ::String
    @map.fetch(value) do
      raise(ValidationError,"unknown value (#{value.inspect})")
    end
  else
    raise(ValidationError,"value must be either a Symbol or a String (#{value.inspect})")
  end
end