Module: Legion::API::Validators
- Defined in:
- lib/legion/api/validators.rb
Constant Summary collapse
- UUID_PATTERN =
/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
Instance Method Summary collapse
- #validate_enum!(value, field:, allowed:) ⇒ Object
- #validate_integer!(value, field:, min: nil, max: nil) ⇒ Object
- #validate_required!(body, *keys) ⇒ Object
- #validate_string_length!(value, field:, max: 255) ⇒ Object
- #validate_uuid!(value, field:) ⇒ Object
Instance Method Details
#validate_enum!(value, field:, allowed:) ⇒ Object
21 22 23 24 25 26 |
# File 'lib/legion/api/validators.rb', line 21 def validate_enum!(value, field:, allowed:) return if value.nil? return if allowed.include?(value.to_s) halt 400, json_error('invalid_value', "#{field} must be one of: #{allowed.join(', ')}", status_code: 400) end |
#validate_integer!(value, field:, min: nil, max: nil) ⇒ Object
35 36 37 38 39 40 41 |
# File 'lib/legion/api/validators.rb', line 35 def validate_integer!(value, field:, min: nil, max: nil) return if value.nil? int_val = value.to_i halt 400, json_error('out_of_range', "#{field} must be >= #{min}", status_code: 400) if min && int_val < min halt 400, json_error('out_of_range', "#{field} must be <= #{max}", status_code: 400) if max && int_val > max end |
#validate_required!(body, *keys) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/legion/api/validators.rb', line 8 def validate_required!(body, *keys) missing = keys.select { |k| body[k].nil? || (body[k].respond_to?(:empty?) && body[k].empty?) } return if missing.empty? halt 400, json_error('missing_fields', "required: #{missing.join(', ')}", status_code: 400) end |
#validate_string_length!(value, field:, max: 255) ⇒ Object
15 16 17 18 19 |
# File 'lib/legion/api/validators.rb', line 15 def validate_string_length!(value, field:, max: 255) return unless value.is_a?(String) && value.length > max halt 400, json_error('field_too_long', "#{field} exceeds #{max} characters", status_code: 400) end |
#validate_uuid!(value, field:) ⇒ Object
28 29 30 31 32 33 |
# File 'lib/legion/api/validators.rb', line 28 def validate_uuid!(value, field:) return if value.nil? return if value.to_s.match?(UUID_PATTERN) halt 400, json_error('invalid_format', "#{field} must be a valid UUID", status_code: 400) end |