Sha256: 1212fb1d73f1e34efc71e54122453fe58d8187408176ff5210e1a9a53efc0335

Contents?: true

Size: 1.9 KB

Versions: 12

Compression:

Stored size: 1.9 KB

Contents

# frozen_string_literal: true

module Grape
  module Validations
    class AttributesIterator
      include Enumerable

      attr_reader :scope

      def initialize(validator, scope, params)
        @scope = scope
        @attrs = validator.attrs
        @original_params = scope.params(params)
        @params = Array.wrap(@original_params)
      end

      def each(&block)
        do_each(@params, &block) # because we need recursion for nested arrays
      end

      private

      def do_each(params_to_process, parent_indicies = [], &block)
        params_to_process.each_with_index do |resource_params, index|
          # when we get arrays of arrays it means that target element located inside array
          # we need this because we want to know parent arrays indicies
          if resource_params.is_a?(Array)
            do_each(resource_params, [index] + parent_indicies, &block)
            next
          end

          if @scope.type == Array
            next unless @original_params.is_a?(Array) # do not validate content of array if it isn't array

            # fill current and parent scopes with correct array indicies
            parent_scope = @scope.parent
            parent_indicies.each do |parent_index|
              parent_scope.index = parent_index
              parent_scope = parent_scope.parent
            end
            @scope.index = index
          end

          yield_attributes(resource_params, @attrs, &block)
        end
      end

      def yield_attributes(_resource_params, _attrs)
        raise NotImplementedError
      end

      # This is a special case so that we can ignore tree's where option
      # values are missing lower down. Unfortunately we can remove this
      # are the parameter parsing stage as they are required to ensure
      # the correct indexing is maintained
      def skip?(val)
        val == Grape::DSL::Parameters::EmptyOptionalValue
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
grape-2.1.1 lib/grape/validations/attributes_iterator.rb
grape-2.1.0 lib/grape/validations/attributes_iterator.rb
grape-2.0.0 lib/grape/validations/attributes_iterator.rb
grape-1.8.0 lib/grape/validations/attributes_iterator.rb
grape-1.7.1 lib/grape/validations/attributes_iterator.rb
grape-1.7.0 lib/grape/validations/attributes_iterator.rb
grape-1.6.2 lib/grape/validations/attributes_iterator.rb
grape-1.6.1 lib/grape/validations/attributes_iterator.rb
grape-1.6.0 lib/grape/validations/attributes_iterator.rb
grape-1.5.3 lib/grape/validations/attributes_iterator.rb
grape-1.5.2 lib/grape/validations/attributes_iterator.rb
grape-1.5.1 lib/grape/validations/attributes_iterator.rb