Sha256: 73ea3be57d9985e4a17094506fe4b74a0d04a8d93e9075ee4a5f8cf6e3b7bc63

Contents?: true

Size: 946 Bytes

Versions: 4

Compression:

Stored size: 946 Bytes

Contents

# frozen_string_literal: true

# 直列に繋いだtaskを順番に実行するクラス
class MedPipe::Pipeline
  def initialize
    @tasks = []
  end

  # @param task [Object] def call(context, prev_result, &block) を実装したクラス
  def apply(task)
    @tasks << task
    self
  end

  # @param context [Hash] Stores data during pipeline execution
  def run(context = {}) = run_task_recursive(context)
  # 展開すると以下のようになる
  # @tasks[0].call(context, nil) do |prev_result|
  #   @tasks[1].call(context, prev_result) do |prev_result|
  #     @tasks[2].call(context, prev_result) do |prev_result|
  #       nil
  #     end
  #   end
  # end

  private

  def run_task_recursive(context, prev_result = nil, task_index = 0)
    return prev_result if task_index >= @tasks.size

    @tasks[task_index]&.call(context, prev_result) do |result|
      run_task_recursive(context, result, task_index + 1)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
med_pipe-0.2.0 lib/med_pipe/pipeline.rb
med_pipe-0.1.1 lib/med_pipe/pipeline.rb
med_pipe-0.1.0.5 lib/med_pipe/pipeline.rb
med_pipe-0.1.0.4 lib/med_pipe/pipeline.rb