Skip to main content

Subscribe to GoRails to get access to this episode and all other pro episodes, and new awesome content every month.

Subscribe Now
Only $19/month

Unlimited access. Cancel anytime.

28 Rails 5.2 ActiveSupport CurrentAttributes & Basecamp 3 Account ID URL Scheme

Episode 234 · March 12, 2018

Rails 5.2's adds CurrentAttributes to give you access to global variables in your apps. We'll use this feature to implement a Rack middleware to build Basecamp 3 style URLs that automatically include the current Account ID in every URL

Rack Middleware ActiveSupport Rails 5.2


Transcripts

No transcripts available. Earn a free month

Discussion


Gravatar
Cool stuff! Thanks

Gravatar

How do you end up testing this with Minitest?
All controllers actions fail because env["REQUEST_PATH"] is nil

NoMethodError: undefined method split' for nil:NilClass
lib/account_middleware.rb:8:in
call'

Gravatar
Hi Chris,

This is great, but just wondering how I might be able to use an account_name rather than the account_id?

So would like the URL to look like: sample.com/coolaccount/posts/1
Gravatar
So I managed to get it mostly working using:

class AccountMiddleware
    def initialize(app)
        @app = app
    end

    def call(env)
        _, username, request_path = env["REQUEST_PATH"].split('/', 3)

        if username
            Current.user = User.where(username: username)

            env["SCRIPT_NAME"]  = "/#{username}"
            env["PATH_INFO"]    = "/#{request_path}"
            env["REQUEST_PATH"] = "/#{request_path}"
            env["REQUEST_URI"]  = "/#{request_path}"
        end

        status, headers, body = @app.call(env)
        [status, headers, body]
    end
end
The problem here, of course, is that I have a problem with URLs such as 'users/sign_up/' where Rails thinks username is 'sign_up'


Gravatar
You will need to whitelist some routes (sign_up...) based on 
env["REQUEST_PATH"]
with a regular expression and skip middleware for those paths. (similar to what Chris did with ensuring account_id is a number)


Gravatar
What's the difference with this approach using middleware, and simply taking accounts out of the path in routes?

resources :accounts, path: '', except: [:index] do
  resources: projects
end

(newbie question)

Login or create an account to join the conversation.