Here’s a minimal, idiomatic Rails example wiring Current.organization into your routes and URL generation using your scoped routes.
class Current < ActiveSupport::CurrentAttributes
attribute :organization
endRails.application.routes.draw do
scope(
path: "(/o/:organization_path)",
constraints: {
organization_path: Gitlab::PathRegex.organization_route_regex
}
) do
draw_all_routes
end
endThis means every route can optionally be prefixed with:
/o/:organization_path
class ApplicationController < ActionController::Base
before_action :set_current_organization
private
def set_current_organization
return unless params[:organization_path]
Current.organization = Organization.find_by!(
path: params[:organization_path]
)
end
endclass ApplicationController < ActionController::Base
def default_url_options
return {} unless Current.organization
{
organization_path: Current.organization.path
}
end
endNow all *_url helpers automatically include /o/:organization_path.
projects_urlGenerates:
https://example.com/o/acme/projects
If Current.organization is nil:
https://example.com/projects
All of these now work automatically:
redirect_to project_url(@project)
link_to "Projects", projects_pathclass ApplicationMailer < ActionMailer::Base
def default_url_options
return {} unless Current.organization
{
organization_path: Current.organization.path
}
end
endclass ExampleJob < ApplicationJob
def perform(organization_id)
Current.organization = Organization.find(organization_id)
ProjectsController.helpers.projects_url
ensure
Current.reset
end
end- Optional org prefix works transparently
- No global mutation
- Thread-safe
- Matches GitLab-style routing
_pathand_urlboth behave correctly
If you want, I can also show:
- enforcing org presence for certain controllers
- how to fall back to subdomain instead of
/o/:path - preventing route generation without
Current.organization - test helpers for this pattern