Skip to content

Instantly share code, notes, and snippets.

@maetl
Created May 14, 2016 09:55
Show Gist options
  • Save maetl/df1b51135a552de74ce809ff07fd7aa2 to your computer and use it in GitHub Desktop.
Save maetl/df1b51135a552de74ce809ff07fd7aa2 to your computer and use it in GitHub Desktop.
require 'eventmachine'
class Pipeline < EM::Completion
def initialize(*steps)
@steps = steps
@steps.each_cons(2) do |pair|
pair.first.callback do |input|
EM.next_tick do
pair.last.call(input)
end
end
end
@steps.last.callback do |input|
succeed(input)
end
super()
end
def call(input)
EM.next_tick do
@steps.first.call(input)
end
end
end
class Step < EM::Completion
def add_worker(&worker)
@worker = worker
end
def call(input)
succeed(@worker.call(input))
end
end
class Transaction
def self.start(input, &block)
transaction = self.new
transaction.instance_eval(&block)
transaction.run(input)
end
def initialize
@steps = []
end
def step(label, &block)
step = Step.new
step.add_worker(&block)
@steps << step
end
def after(&block)
@after = block
end
def run(input)
pipeline = Pipeline.new(*@steps)
pipeline.callback do
@after.call
end
pipeline.call(input)
end
end
EM.run do
Transaction.start("hello") do
step(:first) do |input|
puts input
input.upcase
end
step(:second) do |input|
puts input
"#{input} world"
end
step(:third) do |input|
puts input
input.upcase
end
step(:fourth) do |input|
puts input
end
after do
puts "transaction complete"
EM.stop
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment