Created
June 30, 2021 23:12
-
-
Save v-kolesnikov/7138713dcd46c40f2a43c2843414c0d4 to your computer and use it in GitHub Desktop.
Phoenix-like `pipeline` plugin for Roda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile(true) do | |
gem 'roda' | |
gem 'webrick' | |
end | |
class M1 | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
puts 'M1' | |
@app.call(env) | |
end | |
end | |
class M2 | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
puts 'M2' | |
@app.call(env) | |
end | |
end | |
class Roda | |
module RodaPlugins | |
module Pipeline | |
module ClassMethods | |
def pipeline(id, procs) | |
opts[:pipelines] ||= {} | |
opts[:pipelines][id] = [:itself.to_proc, *procs.reverse].reduce { |app, midleware| midleware.new(app) } | |
end | |
end | |
module InstanceMethods | |
def pipe_through(*pipelines) | |
pipelines.reduce(env) do |acc, pipeline_id| | |
acc = opts[:pipelines][pipeline_id].call(acc) | |
end | |
end | |
end | |
end | |
end | |
end | |
class App < ::Roda | |
plugin Roda::RodaPlugins::Pipeline | |
pipeline(:api, [M1]) | |
pipeline(:web, [M1, M2]) | |
route do |routes| | |
routes.root do | |
'root' | |
end | |
routes.on('foo') do | |
pipe_through(:api) | |
'foo' | |
end | |
routes.on('bar') do | |
pipe_through(:web) | |
'bar' | |
end | |
end | |
end | |
Rack::Server.start(app: App) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment