Sha256: 1e662ff68e53c95659d3319c0313e62f3b993b4f9ba107aab23ddc6e0f3759f1

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 KB

Contents

module Representable
  # Allows to implement a pipeline of filters where a value gets passed in and the result gets
  # passed to the next callable object.
  class Pipeline < Array
    include Uber::Callable

    Stop = Class.new

    # options is mutuable.
    def call(input, options)
      inject(input) do |memo, block|
        res = evaluate(block, memo, options)
        return(Stop)if Stop == res
        res
      end
    end

  private
    def evaluate(block, input, options)
      block.call(input, options)
    end
  end


  # Collect applies a pipeline to each element of input.
  class Collect < Pipeline
    # when stop, the element is skipped. (should that be Skip then?)
    def call(input, options)
      arr = []
      input.each_with_index do |item_fragment, i|
        result = super(item_fragment, options.merge(index: i)) # DISCUSS: NO :fragment set.
        Pipeline::Stop == result ? next : arr << result
      end
      arr
    end

    class Hash < Pipeline
      def call(input, options)
        {}.tap do |hsh|
          input.each { |key, item_fragment|
            hsh[key] = super(item_fragment, options) }# DISCUSS: NO :fragment set.
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
representable-2.4.0.rc3 lib/representable/pipeline.rb
representable-2.4.0.rc2 lib/representable/pipeline.rb
representable-2.4.0.rc1 lib/representable/pipeline.rb