a “Handler”, “Middlewares”, and (an) Application - Handler: WEBRick, Puma, Thin, Unicorn - Middlewares: Rack::Attack, Rack::MethodOverride, ActionDispatch - “Application”: Sinatra, Rails - By default, Rack Handler is WEBrick. - You must specify Rack applications and middlewares in Rack Configuration “config.ru” → ru stands for “rackup” - Latest stable version on RubyGem: 2.0.1 - On this talk, let’s focus on Middleware and App *Hijacking and stream are not covered in this talk
to extend any class - Rack will call you will give you Request ENV - Your App/Middleware should response [], with - HTTP Status code - Response header - Enumerable of body - For middleware: you will be constructed - For app: you must be constructed
"https://rubygems.org" gem "rack", '~> 2.0.1' $ cat config.ru class Meow def call(env) [200, {}, ['Miaw']] end end run Meow.new * We don’t really need Bundler. Just make sure we don’t mess up your file system
= app end def call(env) result = @app.call(env) result[1]['X-Cat-Name'] = %w{ Angora Persia Bobtail }.sample result end end class CatStartTime def initialize(app, ct) @app = app @cat_time = ct end def call(env) result = @app.call(env) result[1]['X-Cat-Start-Time'] = @cat_time.to_s result end end Pass parameters into middleware!
ActiveSupport::Cache::Strategy::LocalCache::Middleware use Rack::Runtime use Rack::MethodOverride use ActionDispatch::RequestId use Rails::Rack::Logger use ActionDispatch::ShowExceptions use WebConsole::Middleware use ActionDispatch::DebugExceptions use ActionDispatch::RemoteIp use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::Migration::CheckPending use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash use Rack::Head use Rack::ConditionalGet use Rack::ETag use Warden::Manager use OmniAuth::Strategies::GoogleOauth2 run SinapsWeb::Application.routes
ActiveSupport::Cache::Strategy::LocalCache::Middleware use Rack::Runtime use Rack::MethodOverride ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← use ActionDispatch::RequestId use Rails::Rack::Logger use ActionDispatch::ShowExceptions use WebConsole::Middleware use ActionDispatch::DebugExceptions use ActionDispatch::RemoteIp use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::Migration::CheckPending use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash use Rack::Head use Rack::ConditionalGet use Rack::ETag use Warden::Manager use OmniAuth::Strategies::GoogleOauth2 run SinapsWeb::Application.routes
before hitting application - Rack Middlewares are universal: It should be plug and play to any Rack-based app, not limited to Rails - (Yes yes. As long as the middleware is not tightly-coupled to Rails) - All demo code available on https://github.com/mufid/rack-talk