DEV Community 👩‍💻👨‍💻

David Paluy
David Paluy

Posted on

Account middleware in Ruby On Rails

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
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

  def call(env)
    request = env
    _, account_id, request_path = request.path.split('/', 3)

    if account_id =~ /\d+/
      if account = Account.find_by(id: account_id)
        Current.account = account
        return [302, { "Location" => "/" }, []]

      request.script_name  = "/#{account_id}"
      request.path_info    = "/#{request_path}"
Enter fullscreen mode Exit fullscreen mode

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

Happy Hacking!

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.