class NRSER::Types::When

Wraps an object as a type, using Ruby's “case equality” `===` to test membership (like a `when` clause in a `case` expression).

Deals with some data loading too.

@note

This was kinda hacked in when my idiot-ass figured out that all this
types BS could fit in real well with Ruby's `===`, allowing types to
be used in `when` clauses.

Previously, {.make} used to see if something was a module,
and turn those into `is_a` types, and turn everything else into
`is`, but this kind of sucked for a bunch of reasons I don't totally
remember.

Now, if a value is not a special case (like `nil`) or already a type,
{.make} turns it into a {When}.

{When} instances are totally Ruby-centric, and are thus mostly to
support in-runtime testing - you wouldn't want a {When} type to
be part of an API schema or something - but they're really nice for
the internal stuff.

Attributes

object[R]

The wrapped {Object} whose `#===` will be used to test membership.

@return [Object]

Public Class Methods

new(object, **options) click to toggle source

Instantiate a new `::When`.

Calls superclass method NRSER::Types::Type::new
# File lib/nrser/types/when.rb, line 59
def initialize object, **options
  super **options
  @object = object
end

Public Instance Methods

==(other) click to toggle source
# File lib/nrser/types/when.rb, line 116
def == other
  equal?( other ) ||
  ( self.class == other.class &&
    self.object == other.object )
end
custom_from_s(string) click to toggle source
# File lib/nrser/types/when.rb, line 83
def custom_from_s string
  object.from_s string
end
explain() click to toggle source
# File lib/nrser/types/when.rb, line 73
def explain
  @object.inspect
end
from_data(data) click to toggle source

If {#object} responds to `#from_data`, call that and check results.

Otherwise, forward up to {::Type#from_data}.

@param [Object] data

Data to create the value from that will satisfy the type.

@return [Object]

Instance of {#object}.
Calls superclass method NRSER::Types::Type#from_data
# File lib/nrser/types/when.rb, line 98
def from_data data
  if @from_data.nil?
    if @object.respond_to? :from_data
      check @object.from_data( data )
    else
      super data
    end
  else
    @from_data.call data
  end
end
has_from_data?() click to toggle source
# File lib/nrser/types/when.rb, line 111
def has_from_data?
  @from_data || @object.respond_to?( :from_data )
end
has_from_s?() click to toggle source
# File lib/nrser/types/when.rb, line 78
def has_from_s?
  @from_s || object.respond_to?( :from_s )
end
test?(value) click to toggle source

Instance Methods

# File lib/nrser/types/when.rb, line 68
def test? value
  @object === value
end