Class: Toys::Settings::Type
- Inherits:
-
Object
- Object
- Toys::Settings::Type
- 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
-
#description ⇒ String
readonly
The name of the type.
Class Method Summary collapse
-
.for_default_value(value) ⇒ Type
Create and return a Type given a default value.
-
.for_type_spec(type_spec) ⇒ Type
Create and return a Type given a type specification.
Instance Method Summary collapse
-
#call(val) ⇒ Object
Test a value, possibly converting to a legal value.
-
#initialize(description, &block) ⇒ Type
constructor
Create a new Type.
Constructor Details
#initialize(description, &block) ⇒ Type
Create a new Type.
370 371 372 373 |
# File 'lib/toys/settings.rb', line 370 def initialize(description, &block) @description = description.freeze @tester = block end |
Instance Attribute Details
#description ⇒ String (readonly)
The name of the type.
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.
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.
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.
388 389 390 |
# File 'lib/toys/settings.rb', line 388 def call(val) @tester.call(val) end |