Sha256: 87b189c965c7bca23606950ed216d17fea97271618f0ce4fea501fcfb90a5908

Contents?: true

Size: 1.33 KB

Versions: 11

Compression:

Stored size: 1.33 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

        iterate { |*args, **opts| yield(*args, **opts) }
      end

      private

      attr_accessor :enumerable, :options, :rules

      def hash?
        enumerable.is_a?(::Hash) || enumerable.respond_to?(:key)
      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)
        Array(enumerable).each_with_index.all? do |array_like_element, i|
          OutputIteratorWithPredicate.call(array_like_element, options.trace(i), rules: rules, &block)
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
media_types-2.0.0 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-1.0.0 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.6.2 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.6.1 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.6.0 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.5 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.4 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.3 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.2 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.1 lib/media_types/scheme/output_iterator_with_predicate.rb
media_types-0.5.0 lib/media_types/scheme/output_iterator_with_predicate.rb