Class: VehicleMakeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/vehicles/validators/vehicle_make_validator.rb

Overview

Drop-in validator: validates :make, vehicle_make: true.

Rails resolves the vehicle_make: key to this top-level constant automatically (camelize + "Validator"), so no registration is needed — requiring the file is enough. Forgiving (aliases/case/slug) like every other lookup, and defensive: blank values pass (pair with presence: true if you want them rejected), and any internal error degrades to a generic message instead of blowing up a form.

Pass allow_other: true to accept the "Other / not in the list" escape hatch (see Vehicles.other?) — pair it with Vehicles.make_options(include_other:) so the dropdown and the validation agree by construction.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/vehicles/validators/vehicle_make_validator.rb', line 15

def validate_each(record, attribute, value)
  return if value.blank?
  return if options[:allow_other] && Vehicles.other?(value)
  return if Vehicles.make(value)

  record.errors.add(attribute, options[:message] || "is not a recognized vehicle make")
rescue StandardError => e
  Vehicles.logger&.error("[vehicles] vehicle_make validation error: #{e.message}")
  record.errors.add(attribute, options[:message] || "is not a recognized vehicle make")
end