Implement multi-tenancy with Context
mainRabarber supports multi-tenancy by allowing roles to be scoped to a context. A context can be an ActiveRecord model instance, a model class, or nil (for global roles).
Contextual Role Management
user.assign_roles(:role, context: object): Assigns a role within a specific instance scope.user.has_role?(:role, context: Class): Checks for a role within a class scope.Rabarber.create_role(:role, context: object): Creates a role within a context.Rabarber.roles(context: object): Lists roles available in a specific context.
Contextual Authorization
In controllers, you can resolve context using a Symbol (instance method) or a Proc:
# Using a method-based context
grant_access action: :show, roles: :member, context: :current_project
# Using a Proc-based context
grant_access action: :update, roles: :owner, context: -> { Project.find(params[:id]) }Maintenance
Rabarber.prune: Cleans up orphaned roles if context objects were deleted from the database without revoking roles.migrate_authorization_context!("OldModel", "NewModel"): Irreversible migration to rename a context class.delete_authorization_context!("ModelName"): Irreversible migration to remove context data for a deleted model.
# Contextual Assignment
user.assign_roles(:owner, context: project)
# Contextual Query
user.has_role?(:owner, context: project)
# Contextual Authorization in Controller
class ProjectsController < ApplicationController
grant_access action: :show, roles: :member, context: :current_project
private
def current_project
@current_project ||= Project.find(params[:id])
end
end