Module: Candid::Internal::Types::Utils
- Defined in:
- lib/candid/internal/types/utils.rb
Overview
Utilities for dealing with and checking types
Class Method Summary collapse
-
.coerce(target, value, strict: false) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity.
- .symbolize_keys(hash) ⇒ Object
-
.unwrap_type(type) ⇒ Object
Resolves a type or type function into a type.
-
.wrap_type(type) ⇒ Proc
Wraps a type into a type function.
Class Method Details
.coerce(target, value, strict: false) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/candid/internal/types/utils.rb', line 29 def self.coerce(target, value, strict: false) # rubocop:disable Metrics/CyclomaticComplexity type = unwrap_type(target) case type in Array case value when ::Array return type.coerce(value, strict: strict) when Set, ::Hash return coerce(type, value.to_a) end in Hash case value when ::Hash return type.coerce(value, strict: strict) when ::Array return coerce(type, value.to_h) end in ->(t) { t <= NilClass } return nil in ->(t) { t <= String } case value when String, Symbol, Numeric, TrueClass, FalseClass return value.to_s end in ->(t) { t <= Symbol } case value when Symbol, String return value.to_sym end in ->(t) { t <= Integer } case value when Numeric, String, Time return value.to_i end in ->(t) { t <= Float } case value when Numeric, Time, String return value.to_f end in ->(t) { t <= Model } case value when type return value when ::Hash return type.coerce(value, strict: strict) end in Module case type in ->(t) { t.singleton_class.included_modules.include?(Enum) } return type.coerce(value, strict: strict) in ->(t) { t.singleton_class.included_modules.include?(Union) } return type.coerce(value, strict: strict) else value end else value end raise Errors::TypeError, "cannot coerce value of type `#{value.class}` to `#{target}`" if strict value end |
.symbolize_keys(hash) ⇒ Object
94 95 96 |
# File 'lib/candid/internal/types/utils.rb', line 94 def self.symbolize_keys(hash) hash.transform_keys(&:to_sym) end |
.unwrap_type(type) ⇒ Object
Resolves a type or type function into a type
25 26 27 |
# File 'lib/candid/internal/types/utils.rb', line 25 def self.unwrap_type(type) type.is_a?(Proc) ? type.call : type end |
.wrap_type(type) ⇒ Proc
Wraps a type into a type function
12 13 14 15 16 17 18 19 |
# File 'lib/candid/internal/types/utils.rb', line 12 def self.wrap_type(type) case type when Proc type else -> { type } end end |