Sha256: e88a71a441f0dfe196ad0ef5d073745ed920d809593fd47d080d068378361833

Contents?: true

Size: 1.31 KB

Versions: 2

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

require "active_support/all"
require "grape"

module Grape
  module ExtraValidators
    class StartWith < Grape::Validations::Base
      # ------------------------------------------------------------------------------------------------------------------------
      # Methods
      # ------------------------------------------------------------------------------------------------------------------------
      # Public Methods
      # ------------------------------------------------------------------------------------------------------------------------
      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
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
grape-extra_validators-2.0.0 lib/grape/extra_validators/start_with.rb
grape-extra_validators-1.0.0 lib/grape/extra_validators/start_with.rb