Class: Brute::Pipeline

Inherits:
Object
  • Object
show all
Defined in:
lib/brute/pipeline.rb

Overview

Generic middleware machinery. Builds a chain of middleware around a terminal app, exposes ‘call(env)` to invoke it.

Subclasses (Agent, Tool) override ‘call` to translate their public arguments into an env hash, then delegate to super.

class MyPipeline < Brute::Pipeline
  def call(input)
    env = { input: input, output: nil }
    super(env)
    env[:output]
  end
end

Direct Known Subclasses

Agent, Tool

Defined Under Namespace

Classes: NullSink

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Pipeline

Returns a new instance of Pipeline.



22
23
24
25
26
# File 'lib/brute/pipeline.rb', line 22

def initialize(&block)
  @middlewares = []
  @app = nil
  instance_eval(&block) if block_given?
end

Instance Method Details

#buildObject

Build the chain without calling it. Useful for inspection or caching.



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/brute/pipeline.rb', line 47

def build
  raise "Stack has no terminal app — call `run` first" unless @app

  @middlewares.reverse.inject(@app) do |inner, (klass, args, kwargs, block)|
    if block
      klass.new(inner, *args, **kwargs, &block)
    else
      klass.new(inner, *args, **kwargs)
    end
  end
end

#call(env) ⇒ Object

Invoke the chain. Subclasses typically override this to shape env and extract a return value.



42
43
44
# File 'lib/brute/pipeline.rb', line 42

def call(env)
  build.call(env)
end

#run(app) ⇒ Object

Set the terminal app (innermost handler). Accepts an instance (anything responding to #call(env)) or a class.



36
37
38
# File 'lib/brute/pipeline.rb', line 36

def run(app)
  tap { @app = app }
end

#use(klass, *args, **kwargs, &block) ⇒ Object

Register a middleware class. The class must implement ‘initialize(app, *args, **kwargs)` and `call(env)`.



30
31
32
# File 'lib/brute/pipeline.rb', line 30

def use(klass, *args, **kwargs, &block)
  tap { @middlewares << [klass, args, kwargs, block] }
end