module Api
  class ValidationsController < ApiController
    # rubocop:disable Metrics/MethodLength
    def prisoner
      begin
        date = Date.parse(params.fetch(:date_of_birth))
      rescue ArgumentError
        raise ParameterError, 'date_of_birth'
      end

      validation = PrisonerValidation.new(
        noms_id: params.fetch(:number),
        date_of_birth: date
      )

      if validation.valid?
        response = { valid: true }
      else
        response = { valid: false, errors: validation.errors.values.flatten }
      end

      render status: 200, json: { validation: response }
    end
    # rubocop:enable Metrics/MethodLength
  end
end

module Api
  class ValidationsController < ApiController
    def prisoner
      date, noms_id = validate_prisoner_parameters(params)

      prisoner = PrisonerValidation.new(noms_id: noms_id, date_of_birth: date)

      if prisoner.valid?
        response = { valid: true }
      else
        response = { valid: false, errors: prisoner.errors.values.flatten }
      end

      render status: 200, json: { validation: response }
    end

  private

    def validate_prisoner_parameters(params)
      begin
        date = Date.parse(params.fetch(:date_of_birth))
      rescue ArgumentError
        raise ParameterError, 'date_of_birth'
      end

      noms_id = params.fetch(:number)

      # TODO: Discuss removing this cop; especially when there are multiple
      # return values I find an explicit return much cleaner.
      # rubocop:disable Style/RedundantReturn
      return date, noms_id
      # rubocop:enable Style/RedundantReturn
    end
  end
end

Refactor param validation for prisoner validation API
Refactor param validation for prisoner validation API

Also renamed the local variable from validation to prisoner to attempt to avoid confusion:

There are two types of validation happening here:

* The validation of API parameters (which happens in the controller)
* The actual validation of the prisoner (which happens in the PrisonerValidation class)

and it’s important that they’re not confused. We did consider renaming PrisonerValidation, but couldn’t come up with a more satisfactory name.