Class: Grape::ExtraValidators::StartWith

Inherits:
Validations::Base
  • Object
show all
Defined in:
lib/grape/extra_validators/start_with.rb

Instance Method Summary collapse

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object


Methods


Public Methods




14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/grape/extra_validators/start_with.rb', line 14

def validate_param!(attr_name, params)
  return if !@required && params[attr_name].blank?

  start_with_values = @option.instance_of?(Array) ? @option : [@option]

  # `to_s` is for Symbol.
  parameter = params[attr_name].presence.to_s
  is_valid = start_with_values.any? { |value| parameter.starts_with?(value.to_s) }
  return if is_valid

  allow_values = start_with_values.map { |value| "\"#{value}\"" }
  allow_values[allow_values.length - 1] = "or #{allow_values.last}" if allow_values.length > 1
  message = "must start with #{allow_values.join(", ")}"
  fail Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: message)
end