Class: MocaRlibs::GrapeValidators::StartsWith

Inherits:
Grape::Validations::Base
  • Object
show all
Defined in:
lib/moca_rlibs/grape_validators/starts_with.rb

Overview

文字列の先頭をチェック

Instance Method Summary collapse

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object

Raises:

  • (Grape::Exceptions::Validation)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/moca_rlibs/grape_validators/starts_with.rb', line 11

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(', ')}"
  raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: message)
end