ルビーのレールのアカウントミドルウェア


各リクエストを特定のアカウントを使用して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
ハッピーハッキング!