Skip to content

Instantly share code, notes, and snippets.

@we4tech
Created August 7, 2018 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save we4tech/fbea5f0a9280087779b51a0527e7f850 to your computer and use it in GitHub Desktop.
Save we4tech/fbea5f0a9280087779b51a0527e7f850 to your computer and use it in GitHub Desktop.
How to chain middleware call in Ruby?
# Create a middleware class
class Middleware
def call(*args)
puts "Args: #{args}"
yield
end
end
def call_in_chain(chain)
traverse_chain = lambda do
if chain.empty?
yield
else
chain.shift.call(chain.size, &traverse_chain)
end
end
traverse_chain.call
end
# Example call
call_in_chain(Array.new(5) { Middleware.new }) { puts 'Finally the unit of work' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment