Class: GraphQL::Schema::Validator::LengthValidator
- Inherits:
-
Validator
- Object
- Validator
- GraphQL::Schema::Validator::LengthValidator
- Defined in:
- lib/graphql/schema/validator/length_validator.rb
Overview
Use this to enforce a .length restriction on incoming values. It works for both Strings and Lists.
Instance Method Summary collapse
-
#initialize(maximum: nil, too_long: "%{validated} is too long (maximum is %{count})", minimum: nil, too_short: "%{validated} is too short (minimum is %{count})", is: nil, within: nil, wrong_length: "%{validated} is the wrong length (should be %{count})", message: nil, **default_options) ⇒ LengthValidator
constructor
A new instance of LengthValidator.
- #validate(_object, _context, value) ⇒ Object
Constructor Details
#initialize(maximum: nil, too_long: "%{validated} is too long (maximum is %{count})", minimum: nil, too_short: "%{validated} is too short (minimum is %{count})", is: nil, within: nil, wrong_length: "%{validated} is the wrong length (should be %{count})", message: nil, **default_options) ⇒ LengthValidator
Returns a new instance of LengthValidator.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/graphql/schema/validator/length_validator.rb', line 25 def initialize( maximum: nil, too_long: "%{validated} is too long (maximum is %{count})", minimum: nil, too_short: "%{validated} is too short (minimum is %{count})", is: nil, within: nil, wrong_length: "%{validated} is the wrong length (should be %{count})", message: nil, ** ) if within && (minimum || maximum) raise ArgumentError, "`length: { ... }` may include `within:` _or_ `minimum:`/`maximum:`, but not both" end # Under the hood, `within` is decomposed into `minimum` and `maximum` @maximum = maximum || (within && within.max) @too_long = || too_long @minimum = minimum || (within && within.min) @too_short = || too_short @is = is @wrong_length = || wrong_length super(**) end |
Instance Method Details
#validate(_object, _context, value) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/graphql/schema/validator/length_validator.rb', line 45 def validate(_object, _context, value) return if permitted_empty_value?(value) # pass in this case length = value.nil? ? 0 : value.length if (current_max = validation_parameter(@maximum)) && length > current_max partial_format(validation_parameter(@too_long), { count: current_max }) elsif (current_min = validation_parameter(@minimum)) && length < current_min partial_format(validation_parameter(@too_short), { count: current_min }) elsif (current_is = validation_parameter(@is)) && length != current_is partial_format(validation_parameter(@wrong_length), { count: current_is }) end end |