やったこと
Rails5 で自作したミドルウェアを読み込んで使ってみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
調査
現在のミドルウェア
$ bin/rails middleware
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Sprockets::Rails::QuietAssets
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use WebConsole::Middleware
use ActionDispatch::DebugExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ContentSecurityPolicy::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Rack::TempfileReaper
run Sample2::Application.routes
lib/middlewares/my_middleware.rb
class MyMiddleware
def initialize(app)
@app = app
end
def call(env)
if env['PATH_INFO'] == '/tasks/new'
Rails.logger.debug('path is /tasks/new')
res = @app.call(env)
else
Rails.logger.debug('path is other')
res = @app.call(env)
end
res
end
end
config/application.rb
require './lib/middlewares/my_middleware'
...
module Sample2
class Application < Rails::Application
...
config.middleware.use ::MyMiddleware
end
end
$ bin/rails middleware | grep My
use MyMiddleware