Module: Stannum::Support::Coercion
- Defined in:
- lib/stannum/support/coercion.rb
Overview
Shared functionality for coercing values to and from constraints.
Class Method Summary collapse
-
.error_key(value) ⇒ Integer, ...
Coerces an arbitrary object into a valid Stannum::Errors key.
-
.presence_constraint(present, allow_nil: false, as: 'present', **options) {|present, options| ... } ⇒ Stannum::Constraints:Base?
Coerce a Boolean value to a Presence constraint.
-
.type_constraint(value, allow_nil: false, as: 'type', **options) {|value, options| ... } ⇒ Stannum::Constraints:Base?
Coerce a Class or Module to a Type constraint.
Class Method Details
.error_key(value) ⇒ Integer, ...
Coerces an arbitrary object into a valid Stannum::Errors key.
If the value is an Integer, a String, or a Symbol, returns the value. Otherwise, returns the result of calling #inspect on the value.
22 23 24 25 26 |
# File 'lib/stannum/support/coercion.rb', line 22 def error_key(value) return value if ERROR_KEY_TYPES.include?(value.class) value.inspect end |
.presence_constraint(present, allow_nil: false, as: 'present', **options) {|present, options| ... } ⇒ Stannum::Constraints:Base?
Coerce a Boolean value to a Presence constraint.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/stannum/support/coercion.rb', line 51 def presence_constraint( present, allow_nil: false, as: 'present', **, &block ) return nil if allow_nil && present.nil? if present.is_a?(Stannum::Constraints::Base) return present.(**) end if present == true || present == false # rubocop:disable Style/MultipleComparison return build_presence_constraint(present, **, &block) end raise ArgumentError, "#{as} must be true or false or a constraint", caller(1..-1) end |
.type_constraint(value, allow_nil: false, as: 'type', **options) {|value, options| ... } ⇒ Stannum::Constraints:Base?
Coerce a Class or Module to a Type constraint.
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/stannum/support/coercion.rb', line 94 def type_constraint( value, allow_nil: false, as: 'type', **, &block ) return nil if allow_nil && value.nil? if value.is_a?(Stannum::Constraints::Base) return value.(**) end if value.is_a?(Module) return build_type_constraint(value, **, &block) end raise ArgumentError, "#{as} must be a Class or Module or a constraint", caller(1..-1) end |