DEV Community

David Paluy
David Paluy

Posted on

2 2

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more