Skip to main content

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

General • Asked by Chris Oliver

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'

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


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)


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.

Subscribe to the newsletter

Join 20,000+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.