Class: Ukiryu::Validation::RangeConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/ukiryu/validation/constraints.rb

Overview

Validates numeric or array length ranges

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Constraint

#applies_to?

Constructor Details

#initialize(attribute_name, min:, max:) ⇒ RangeConstraint

Returns a new instance of RangeConstraint.

Parameters:

  • attribute_name (String, Symbol)

    the attribute name

  • min (Numeric)

    minimum value

  • max (Numeric)

    maximum value



64
65
66
67
68
# File 'lib/ukiryu/validation/constraints.rb', line 64

def initialize(attribute_name, min:, max:)
  @attribute_name = attribute_name
  @min = min
  @max = max
end

Instance Attribute Details

#attribute_nameObject (readonly)

Returns the value of attribute attribute_name.



59
60
61
# File 'lib/ukiryu/validation/constraints.rb', line 59

def attribute_name
  @attribute_name
end

#maxObject (readonly)

Returns the value of attribute max.



59
60
61
# File 'lib/ukiryu/validation/constraints.rb', line 59

def max
  @max
end

#minObject (readonly)

Returns the value of attribute min.



59
60
61
# File 'lib/ukiryu/validation/constraints.rb', line 59

def min
  @min
end

Instance Method Details

#validate(value, _context = {}) ⇒ Object

Raises:

  • (ValidationError)

    if value is outside range



71
72
73
74
75
76
77
78
79
80
# File 'lib/ukiryu/validation/constraints.rb', line 71

def validate(value, _context = {})
  return if value.nil?

  check_value = value.is_a?(Array) ? value.size : value

  return unless check_value < @min || check_value > @max

  raise ValidationIssue.new(@attribute_name, :range,
                            "#{@attribute_name} must be between #{@min} and #{@max}, got #{check_value}")
end