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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay