Class: Highway::Steps::Types::AnyOf

Inherits:
Any
  • Object
show all
Defined in:
lib/highway/steps/types/anyof.rb

Overview

This class represents a parameter type that's any of given types.

Instance Method Summary collapse

Methods inherited from Any

#typecheck_and_validate, #validate

Constructor Details

#initialize(**type_defs) ⇒ AnyOf

Initialize an instance.

The variadic argument accepts types keyed by a tag symbol. Tags are used to later denote which type the value falls to.

Consider a step which defines the following parameter:

Types::AnyOf(
  channel: Types::String.regex(/#\w+/),
  user: Types::String.regex(/@\w+/),
)

Later, when a step which defined such a parameter receives a value, it doesn't receive just a plain String, it receives:

{ tag: :channel, value: "#general" }

Thus retaining the information about which type definition matched the value.

Parameters:

  • Type definitions. First match wins.



42
43
44
45
# File 'lib/highway/steps/types/anyof.rb', line 42

def initialize(**type_defs)
  super(validate: nil)
  @type_defs = type_defs
end

Instance Method Details

#typecheck(value) ⇒ Object?

Typecheck and coerce a value if possible.

This method returns a typechecked and coerced value or nil if value has invalid type and can't be coerced.

Parameters:

  • A value.

Returns:



55
56
57
58
# File 'lib/highway/steps/types/anyof.rb', line 55

def typecheck(value)
  typechecked_defs = @type_defs.map { |tag, type| {tag: tag, value: type.typecheck_and_validate(value) } }
  typechecked_defs.find { |typechecked_def| typechecked_def[:value] != nil }
end