Sha256: f5ea062a064ecdaa44d14f3ec727bad20f84eec78b76b6a02c6ac137a4fb0296

Contents?: true

Size: 1.55 KB

Versions: 15

Compression:

Stored size: 1.55 KB

Contents

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
            inside_array = true
          end
          if inside_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

          @attrs.each do |attr_name|
            yield resource_params, attr_name, inside_array
          end
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
grape-1.2.4 lib/grape/validations/attributes_iterator.rb
grape-1.2.3 lib/grape/validations/attributes_iterator.rb
grape-1.2.2 lib/grape/validations/attributes_iterator.rb
grape-1.2.1 lib/grape/validations/attributes_iterator.rb
grape-1.2.0 lib/grape/validations/attributes_iterator.rb
grape-1.1.0 lib/grape/validations/attributes_iterator.rb
grape-1.0.3 lib/grape/validations/attributes_iterator.rb
grape-1.0.2 lib/grape/validations/attributes_iterator.rb
grape-1.0.1 lib/grape/validations/attributes_iterator.rb
grape-1.0.0 lib/grape/validations/attributes_iterator.rb
grape-0.19.2 lib/grape/validations/attributes_iterator.rb
grape-0.19.1 lib/grape/validations/attributes_iterator.rb
grape-0.19.0 lib/grape/validations/attributes_iterator.rb
grape-0.18.0 lib/grape/validations/attributes_iterator.rb
grape-0.17.0 lib/grape/validations/attributes_iterator.rb