Account middleware in Ruby On Rails

David Paluy - Aug 22 '20 - - Dev Community

If you want to identify each request to your Rails application with specific account, you don't have to change your routes.rb

Instead, you can use Custom Middleware to implement this option.

First, let's use ActiveSupport::CurrentAttributes. It will simplify the per-request attributes access.

# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
  attribute :account
end
Enter fullscreen mode Exit fullscreen mode

This is our AccountMiddlreware that will identify an Account by the id, and update the request path accordingly.

# 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
Enter fullscreen mode Exit fullscreen mode

Note:
request.script_name is required to overwrite other links on the page. Otherwise, the new link will be: /projects/new
w/o the account_id.

Add the middleware to your application and restart your Rails server.

# config/application.rb

require_relative '../lib/account_middleware'

class Application < Rails::Application
  # ...

  config.middleware.use AccountMiddleware
end
Enter fullscreen mode Exit fullscreen mode

Happy Hacking!

. . . . . . . . . . . . . . . .