Sha256: 7c7c5b1166110eb3b46e2db14bff8fa948a2f1ba5f17125070d6d8f151dc9d65

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

require 'media_types/scheme/enumeration_context'

module MediaTypes
  class Scheme
    class OutputIteratorWithPredicate

      class << self
        def call(*args, **opts, &block)
          new(*args, **opts).call(&block)
        end
      end

      def initialize(enumerable, options, rules:)
        self.enumerable = enumerable
        self.options = options
        self.rules = rules
      end

      ##
      # Mimics Enumerable#all? with mandatory +&block+
      #
      def call
        if hash?
          return iterate_hash { |*args, **opts| yield(*args, **opts) }
        end

        if array?
          return iterate { |*args, **opts| yield(*args, **opts) }
        end

        raise "Internal consistency error, unexpected: #{enumerable.class}"
      end

      private

      attr_accessor :enumerable, :options, :rules

      def hash?
        enumerable.is_a?(::Hash) || enumerable.respond_to?(:key)
      end

      def array?
        enumerable.is_a?(::Array)
      end

      def iterate_hash
        context = EnumerationContext.new(rules: rules)

        enumerable.all? do |key, value|
          yield key, value, options: options, context: context.enumerate(key)
        end
      end

      def iterate(&block)
        hash_rule = Rules.new(allow_empty: false, expected_type: ::Hash)

        enumerable.each_with_index.all? do |array_like_element, i|
          OutputTypeGuard.call(array_like_element, options.trace(1), rules: hash_rule)
          OutputIteratorWithPredicate.call(array_like_element, options.trace(i), rules: rules, &block)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
media_types-2.3.0 lib/media_types/scheme/output_iterator_with_predicate.rb