Class: Grape::Validations::Types::DryTypeCoercer
- Inherits:
-
Object
- Object
- Grape::Validations::Types::DryTypeCoercer
- Defined in:
- lib/grape/validations/types/dry_type_coercer.rb
Overview
A base class for classes which must identify a coercer to be used. If the strict argument is true, it won’t coerce the given value but check its type. More information there dry-rb.org/gems/dry-types/main/built-in-types/
Direct Known Subclasses
Class Method Summary collapse
-
.coercer_instance_for(type, strict = false) ⇒ Object
Returns an instance of a coercer for a given type.
-
.collection_coercer_for(type) ⇒ Object
Returns a collection coercer which corresponds to a given type.
Instance Method Summary collapse
-
#call(val) ⇒ Object
Coerces the given value to a type which was specified during initialization as a type argument.
-
#initialize(type, strict = false) ⇒ DryTypeCoercer
constructor
A new instance of DryTypeCoercer.
Constructor Details
#initialize(type, strict = false) ⇒ DryTypeCoercer
Returns a new instance of DryTypeCoercer.
35 36 37 38 39 |
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 35 def initialize(type, strict = false) @type = type @strict = strict @cache_coercer = strict ? DryTypes::StrictCache : DryTypes::ParamsCache end |
Class Method Details
.coercer_instance_for(type, strict = false) ⇒ Object
Returns an instance of a coercer for a given type
29 30 31 32 |
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 29 def coercer_instance_for(type, strict = false) klass = type.instance_of?(Class) ? PrimitiveCoercer : collection_coercer_for(type) klass.new(type, strict) end |
.collection_coercer_for(type) ⇒ Object
Returns a collection coercer which corresponds to a given type. Example:
collection_coercer_for(Array)
#=> Grape::Validations::Types::ArrayCoercer
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 17 def collection_coercer_for(type) case type when Array ArrayCoercer when Set SetCoercer else raise ArgumentError, "Unknown type: #{type}" end end |
Instance Method Details
#call(val) ⇒ Object
Coerces the given value to a type which was specified during initialization as a type argument.
45 46 47 48 49 50 51 |
# File 'lib/grape/validations/types/dry_type_coercer.rb', line 45 def call(val) return if val.nil? @coercer[val] rescue Dry::Types::CoercionError InvalidValue.new end |