Class: Toys::Settings::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/toys/settings.rb

Overview

A type object that checks values.

A Type includes a description string and a testing function. The testing function takes a proposed value and returns either the value itself if it is valid, a converted value if the value can be converted to a valid value, or ILLEGAL_VALUE if the type check failed.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(description, &block) ⇒ Type

Create a new Type.

Parameters:

  • description (String)

    Name of the type.

  • block (Proc)

    A testing function.



370
371
372
373
# File 'lib/toys/settings.rb', line 370

def initialize(description, &block)
  @description = description.freeze
  @tester = block
end

Instance Attribute Details

#descriptionString (readonly)

The name of the type.

Returns:

  • (String)


379
380
381
# File 'lib/toys/settings.rb', line 379

def description
  @description
end

Class Method Details

.for_default_value(value) ⇒ Type

Create and return a Type given a default value. See the Toys::Settings class documentation for the rules.

Parameters:

  • value (Object)

Returns:



429
430
431
432
433
434
435
436
437
438
# File 'lib/toys/settings.rb', line 429

def for_default_value(value)
  case value
  when nil
    for_module(::Object)
  when true, false
    for_union([true, false])
  else
    for_module(value.class)
  end
end

.for_type_spec(type_spec) ⇒ Type

Create and return a Type given a type specification. See the Toys::Settings class documentation for valid type specifications.

Parameters:

  • type_spec (Object)

Returns:

Raises:

  • (ArgumentError)

    if the type specification is invalid.



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/toys/settings.rb', line 401

def for_type_spec(type_spec)
  case type_spec
  when Type
    type_spec
  when ::Module
    for_module(type_spec)
  when ::Range
    for_range(type_spec)
  when ::Regexp
    for_regexp(type_spec)
  when ::Array
    for_union(type_spec)
  when ::Proc
    new("(opaque proc)", &type_spec)
  when nil, true, false, ::String, ::Symbol, ::Numeric
    for_scalar(type_spec)
  else
    raise ::ArgumentError, "Illegal type spec: #{type_spec.inspect}"
  end
end

Instance Method Details

#call(val) ⇒ Object

Test a value, possibly converting to a legal value.

Parameters:

  • val (Object)

    The value to be tested.

Returns:

  • (Object)

    The validated value, the value converted to a legal value, or ILLEGAL_VALUE if the type check is unsuccessful.



388
389
390
# File 'lib/toys/settings.rb', line 388

def call(val)
  @tester.call(val)
end