ルビーのレールのアカウントミドルウェア
4640 ワード
各リクエストを特定のアカウントを使用してRailsアプリケーションに識別する場合は、変更する必要はありません
まず、使いましょうActiveSupport::CurrentAttributes . これは、要求ごとの属性アクセスを簡素化します.
ミドルウェアをアプリケーションに追加し、Railsサーバーを再起動します.
routes.rb
代わりに、このオプションを実装するカスタムミドルウェアを使用できます.まず、使いましょうActiveSupport::CurrentAttributes . これは、要求ごとの属性アクセスを簡素化します.
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :account
end
これが我々AccountMiddlreware
それはIDによってアカウントを特定し、それに応じてリクエストパスを更新します.# lib/acount_middleware.rb
class AccountMiddleware
def initialize(app)
@app = app
end
# https://youapp.com/12345/projects
def call(env)
request = ActionDispatch::Request.new env
_, account_id, request_path = request.path.split('/', 3)
if account_id =~ /\d+/
if account = Account.find_by(id: account_id)
Current.account = account
else
return [302, { "Location" => "/" }, []]
end
request.script_name = "/#{account_id}"
request.path_info = "/#{request_path}"
end
@app.call(request.env)
end
end
注意:request.script_name
ページの他のリンクを上書きする必要があります.さもなければ、新しいリンクは以下の通りです./projects/new
ワット/Oaccount_id
.ミドルウェアをアプリケーションに追加し、Railsサーバーを再起動します.
# config/application.rb
require_relative '../lib/account_middleware'
class Application < Rails::Application
# ...
config.middleware.use AccountMiddleware
end
ハッピーハッキング!Reference
この問題について(ルビーのレールのアカウントミドルウェア), 我々は、より多くの情報をここで見つけました https://dev.to/dpaluy/account-middleware-in-ruby-on-rails-1a9lテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol