Class: Grape::Validations::Validators::LengthValidator
- Defined in:
- lib/grape/validations/validators/length_validator.rb
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
- #build_message ⇒ Object
-
#initialize(attrs, options, required, scope, **opts) ⇒ LengthValidator
constructor
A new instance of LengthValidator.
- #validate_param!(attr_name, params) ⇒ Object
Methods inherited from Base
#fail_fast?, inherited, #message, #options_key?, #validate, #validate!
Constructor Details
#initialize(attrs, options, required, scope, **opts) ⇒ LengthValidator
Returns a new instance of LengthValidator.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/grape/validations/validators/length_validator.rb', line 7 def initialize(attrs, , required, scope, **opts) @min = [:min] @max = [:max] @is = [:is] super raise ArgumentError, 'min must be an integer greater than or equal to zero' if !@min.nil? && (!@min.is_a?(Integer) || @min.negative?) raise ArgumentError, 'max must be an integer greater than or equal to zero' if !@max.nil? && (!@max.is_a?(Integer) || @max.negative?) raise ArgumentError, "min #{@min} cannot be greater than max #{@max}" if !@min.nil? && !@max.nil? && @min > @max return if @is.nil? raise ArgumentError, 'is must be an integer greater than zero' if !@is.is_a?(Integer) || !@is.positive? raise ArgumentError, 'is cannot be combined with min or max' if !@min.nil? || !@max.nil? end |
Instance Method Details
#build_message ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/grape/validations/validators/length_validator.rb', line 33 def if (:message) @option[:message] elsif @min && @max format I18n.t(:length, scope: 'grape.errors.messages'), min: @min, max: @max elsif @min format I18n.t(:length_min, scope: 'grape.errors.messages'), min: @min elsif @max format I18n.t(:length_max, scope: 'grape.errors.messages'), max: @max else format I18n.t(:length_is, scope: 'grape.errors.messages'), is: @is end end |
#validate_param!(attr_name, params) ⇒ Object
23 24 25 26 27 28 29 30 31 |
# File 'lib/grape/validations/validators/length_validator.rb', line 23 def validate_param!(attr_name, params) param = params[attr_name] return unless param.respond_to?(:length) return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max) || (!@is.nil? && param.length != @is) raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: ) end |