Class: Enumpath::Resolver::Simple

Inherits:
Object
  • Object
show all
Defined in:
lib/enumpath/resolver/simple.rb

Overview

A utility for resolving a string as an index, key, or member of an enumerable

Constant Summary collapse

NUMERIC_INDEX_TEST =
/\A\-?(?:0|[1-9][0-9]*)\z/
DATA_CLASS =

Ruby's Data class (3.2 and later), or nil on older Rubies. Older Rubies have an unrelated, deprecated Data constant, so it is only looked up on 3.2 and later.

((RUBY_VERSION.split('.').map(&:to_i) <=> [3, 2]) >= 0 ? Object.const_get(:Data) : nil)

Class Method Summary collapse

Class Method Details

.resolve(variable, enum) ⇒ Object

Attempts to resolve a string as an index, key, or member of an enumerable. Members of Data objects (Ruby 3.2 and later) resolve like Struct members.

Parameters:

  • variable (String) —

    the value to attempt to resolve

  • enum (Enumerable) —

    the enumerable to resolve the value against

Returns:

  • the resolved value, or nil if it could not be resolved



20
21
22
23
24
25
26
27
# File 'lib/enumpath/resolver/simple.rb', line 20

def resolve(variable, enum)
  variable = variable.to_s
  value = rescued_dig(enum, variable.to_i) if variable =~ NUMERIC_INDEX_TEST
  value = rescued_dig(enum, variable) if value.nil?
  value = rescued_dig(enum, variable.to_sym) if value.nil?
  value = data_member(enum, variable) if value.nil?
  value
end