### Setup Development Dependencies
Source: https://github.com/enjaku4/rabarber/blob/main/CONTRIBUTING.md
Installs the necessary dependencies for local development of the Rabarber project. This command should be run after forking the repository and cloning it locally.
```shell
bin/setup
```
--------------------------------
### Install Rabarber Gem
Source: https://context7.com/enjaku4/rabarber/llms.txt
Add the Rabarber gem to your application's Gemfile and run bundle install to install it. This is the first step in setting up Rabarber for role-based authorization.
```ruby
# Gemfile
gem "rabarber"
```
```bash
# Install the gem
bundle install
```
--------------------------------
### Start Developer Console
Source: https://github.com/enjaku4/rabarber/blob/main/CONTRIBUTING.md
Launches an interactive Ruby console environment for Rabarber, allowing for experimentation and debugging during development.
```shell
bin/console
```
--------------------------------
### Install Rabarber Gem
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Adds the Rabarber gem to your project's Gemfile and installs it using Bundler.
```ruby
gem "rabarber"
```
```shell
bundle install
```
--------------------------------
### Conditional Rendering with Rabarber View Helpers
Source: https://context7.com/enjaku4/rabarber/llms.txt
These ERB examples demonstrate using Rabarber's `visible_to` and `hidden_from` view helpers to conditionally render content based on user roles and contexts in Rails views.
```erb
<%= visible_to(:admin, :manager) do %>
Administration Panel
<%= link_to "Manage Users", admin_users_path %>
<%= link_to "System Settings", admin_settings_path %>
<% end %>
<%= hidden_from(:guest) do %>
Member Features
<%= link_to "My Profile", profile_path %>
<% end %>
<%= visible_to(:owner, context: @project) do %>
<%= link_to "Project Settings", edit_project_path(@project) %>
<%= button_to "Delete Project", project_path(@project), method: :delete %>
<% end %>
<%= visible_to(:admin, context: Project) do %>
<%= link_to "All Projects", admin_projects_path %>
<% end %>
<%= visible_to(:member) do %>
Member Area
<%= hidden_from(:suspended) do %>
<%= link_to "Post Comment", new_comment_path %>
<% end %>
<% end %>
```
--------------------------------
### Query User Roles
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Methods to check for the presence of specific roles, retrieve a user's roles in the global context, or get all roles grouped by context. Also includes a class method to find users with specific roles.
```ruby
# Check if user has any of the specified roles
user.has_role?(:accountant, :manager)
# Get user's roles in the global context
user.roles
# Get all user's roles grouped by context
user.all_roles
# Get users with any of the specified roles
User.with_role(:admin, :manager)
```
--------------------------------
### Controller Authorization with Method Conditions - Ruby
Source: https://context7.com/enjaku4/rabarber/llms.txt
Defines access control rules for controller actions based on user roles and custom method conditions. This example shows how to grant access to managers and clients based on specific criteria like company affiliation and suspension status.
```ruby
class OrdersController < ApplicationController
# Method-based conditions
grant_access roles: :manager, if: :company_manager?, unless: :suspended?
# Proc-based conditions with parameter access
grant_access action: :show, roles: :client, if: -> { current_user.company == Order.find(params[:id]).company }
def show
# Accessible to company managers unless suspended,
# and to clients if the client's company matches the order's company
@order = Order.find(params[:id])
end
# Dynamic-only rules (no roles required)
grant_access action: :index, if: -> { OrdersPolicy.new(current_user).index? }
def index
# Accessible to company managers unless suspended,
# and to users based on custom policy logic
@orders = Order.all
end
# Multiple conditions (all must pass)
grant_access action: :update, roles: :editor, if: :can_edit?, unless: :locked?
def update
@order = Order.find(params[:id])
@order.update(order_params)
end
private
def company_manager?
current_user.manager_of?(Company.find(params[:company_id]))
end
def suspended?
current_user.suspended?
end
def can_edit?
Order.find(params[:id]).editable_by?(current_user)
end
def locked?
Order.find(params[:id]).locked?
end
end
```
--------------------------------
### Implement Contextual Authorization Rules in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Demonstrates how to apply authorization rules within specific contexts using the `context` option in `grant_access`, including method-based and proc-based context resolution.
```ruby
class ProjectsController < ApplicationController
grant_access roles: :admin, context: Project
# Method-based context resolution
grant_access action: :show, roles: :member, context: :current_project
def show
# Accessible to Project admin and members of the current project
end
# Proc-based context resolution
grant_access action: :update, roles: :owner, context: -> { Project.find(params[:id]) }
def update
# Accessible to Project admin and owner of the current project
end
private
def current_project
@current_project ||= Project.find(params[:id])
end
end
```
--------------------------------
### Implement Dynamic Authorization Rules with Conditions in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Demonstrates using `if` and `unless` options with method or proc-based conditions in `grant_access` to create dynamic authorization rules that depend on runtime logic.
```ruby
class OrdersController < ApplicationController
# Method-based conditions
grant_access roles: :manager, if: :company_manager?, unless: :suspended?
# Proc-based conditions
grant_access action: :show, roles: :client, if: -> { current_user.company == Order.find(params[:id]).company }
def show
# Accessible to company managers unless suspended, and to clients if the client's company matches the order's company
end
# Dynamic-only rules (no roles required, can be used with custom policies)
grant_access action: :index, if: -> { OrdersPolicy.new(current_user).index? }
def index
# Accessible to company managers unless suspended, and to users based on custom policy logic
end
private
def company_manager?
current_user.manager_of?(Company.find(params[:company_id]))
end
def suspended?
current_user.suspended?
end
end
```
--------------------------------
### Set Up Controller Authorization with Rabarber
Source: https://context7.com/enjaku4/rabarber/llms.txt
Integrate Rabarber's controller-level authorization by including the `Rabarber::Authorization` module in your `ApplicationController`. You can then apply authorization globally using `with_authorization` or selectively for specific actions using the `only` or `except` options.
```ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Rabarber::Authorization
# Enable authorization for all actions
with_authorization
end
# app/controllers/invoices_controller.rb
class InvoicesController < ApplicationController
# Selective authorization for specific actions
with_authorization only: [:update, :destroy]
def index
# No authorization required
end
def update
# Authorization required
end
def destroy
# Authorization required
end
end
```
--------------------------------
### Contextual Role Assignment and Checking - Ruby
Source: https://context7.com/enjaku4/rabarber/llms.txt
Demonstrates how to assign and check user roles within specific contexts, such as project or company instances. This is useful for multi-tenant applications where roles might differ based on the tenant or resource. It covers assigning roles to model instances and classes, checking for roles, and retrieving roles within contexts.
```ruby
# Get models
user = User.find(1)
project = Project.find(10)
company = Company.find(5)
# Assign roles within a specific model instance
user.assign_roles(:owner, context: project)
# => [:owner]
user.assign_roles(:member, context: project)
# => [:owner, :member]
# Assign roles within a model class (global to all instances of that type)
user.assign_roles(:admin, context: Project)
# => [:admin]
# Check contextual roles
user.has_role?(:owner, context: project)
# => true
user.has_role?(:admin, context: Project)
# => true
user.has_role?(:owner, context: company)
# => false
# Get user roles in specific contexts
user.roles(context: project)
# => [:owner, :member]
user.roles(context: Project)
# => [:admin]
# Revoke contextual roles
user.revoke_roles(:owner, context: project)
# => [:member]
# Query users with contextual roles
User.with_role(:member, context: project)
# => #, #]>
```
--------------------------------
### Define Controller and Action-Specific Access Rules in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Demonstrates how to use `grant_access` to define controller-wide and action-specific authorization rules based on user roles. Rules can be applied globally or to individual actions within a controller.
```ruby
class TicketsController < ApplicationController
# Controller-wide access
grant_access roles: :admin
# Action-specific access
grant_access action: :index, roles: [:manager, :support]
def index
# Accessible to admin, manager, and support roles
end
def destroy
# Accessible to admin role only
end
end
```
--------------------------------
### Generate and Run Rabarber Roles Migration
Source: https://context7.com/enjaku4/rabarber/llms.txt
Generate the necessary migration for Rabarber roles, specifying user model and ID type (integer or UUID). Then, run the migration to create the roles table.
```bash
# Generate migration for standard integer IDs
rails generate rabarber:roles users
# Or for UUID primary keys
rails generate rabarber:roles users --uuid
# Run the migration
rails db:migrate
```
--------------------------------
### Configure Unrestricted Access and Mixed Authorization in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Shows how to grant unrestricted access to all users by omitting roles in `grant_access`. It also demonstrates a controller with a mix of unrestricted and role-restricted actions.
```ruby
class UnrestrictedController < ApplicationController
grant_access # Allow all users to access all actions
end
class MixedController < ApplicationController
grant_access action: :index # Unrestricted index action
def index
# Accessible to all users
end
grant_access action: :show, roles: :member # Restricted show action
def show
# Accessible to members only
end
end
```
--------------------------------
### Run Tests
Source: https://github.com/enjaku4/rabarber/blob/main/CONTRIBUTING.md
Executes the test suite for the Rabarber project to ensure code quality and identify regressions. This command is typically run after making code changes.
```shell
bin/rspec
```
--------------------------------
### Run Linter
Source: https://github.com/enjaku4/rabarber/blob/main/CONTRIBUTING.md
Applies the RuboCop linter to check code style and identify potential issues in the Rabarber project. This helps maintain code consistency across the project.
```shell
bin/rubocop
```
--------------------------------
### Contextual Controller Authorization Rules - Ruby
Source: https://context7.com/enjaku4/rabarber/llms.txt
Illustrates how to define authorization rules in controllers that depend on specific contexts, such as the current project or a dynamically resolved resource. This allows for hierarchical or resource-specific access control within controllers.
```ruby
# app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
# Class-level context (applies to all Project instances)
grant_access roles: :admin, context: Project
# Method-based context resolution
grant_access action: :show, roles: :member, context: :current_project
def show
# Accessible to Project admin and members of the current project
@project = current_project
end
# Proc-based context resolution
grant_access action: :update, roles: :owner, context: -> { Project.find(params[:id]) }
def update
# Accessible to Project admin and owner of the current project
@project = Project.find(params[:id])
@project.update(project_params)
end
# Multiple contexts with dynamic rules
grant_access action: :destroy, roles: :admin, context: :current_project, if: :can_delete?
def destroy
@project = current_project
@project.destroy
end
private
def current_project
@current_project ||= Project.find(params[:id])
end
def can_delete?
current_project.deletable?
end
end
# app/controllers/tasks_controller.rb
class TasksController < ApplicationController
# Nested context resolution
grant_access roles: :project_member, context: -> { Task.find(params[:id]).project }
def show
@task = Task.find(params[:id])
end
end
```
--------------------------------
### Implement Additive Authorization Rules Across Inheritance in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Illustrates how authorization rules are additive across controller inheritance. Rules defined in a base controller and a derived controller are combined, and multiple rules for the same action are also aggregated.
```ruby
class BaseController < ApplicationController
grant_access roles: :admin # Admin can access everything
end
class InvoicesController < BaseController
grant_access roles: :accountant # Accountant can also access InvoicesController (along with admin)
grant_access action: :index, roles: :manager
grant_access action: :index, roles: :supervisor
def index
# Index is accessible to admin, accountant, manager, and supervisor
end
end
```
--------------------------------
### Automatic Cleanup of Orphaned Roles
Source: https://context7.com/enjaku4/rabarber/llms.txt
This Ruby code demonstrates automatic cleanup for deleted context objects by finding a project and destroying it, which then prunes orphaned roles using the Rabarber library.
```ruby
# Automatic cleanup for deleted context objects
# If you delete a project instance, roles become orphaned
project = Project.find(10)
project.destroy
# Clean up all orphaned roles
Rabarber.prune
```
--------------------------------
### Additive Authorization Rules with Inheritance
Source: https://context7.com/enjaku4/rabarber/llms.txt
Demonstrates additive authorization rules in Rabarber, where rules accumulate across inheritance chains and multiple declarations. This allows for granular control by combining base controller rules with specific controller rules.
```ruby
# app/controllers/base_controller.rb
class BaseController < ApplicationController
# Admin can access everything
grant_access roles: :admin
end
# app/controllers/invoices_controller.rb
class InvoicesController < BaseController
# Accountant can also access InvoicesController (along with admin)
grant_access roles: :accountant
# Multiple grant_access for the same action are additive
grant_access action: :index, roles: :manager
grant_access action: :index, roles: :supervisor
def index
# Index is accessible to admin, accountant, manager, and supervisor
@invoices = Invoice.all
end
def show
# Show is accessible to admin and accountant (no additional rules)
@invoice = Invoice.find(params[:id])
end
end
```
--------------------------------
### Manage Contextual Roles Creation and Deletion in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Details how to create, rename, delete, and list roles within specific contexts using Rabarber's class methods like `create_role`, `rename_role`, `delete_role`, and `roles`.
```ruby
# Create a new role within a context
Rabarber.create_role(:admin, context: Project)
# Rename a role within a context
Rabarber.rename_role(:admin, :owner, context: project)
# Remove a contextual role
Rabarber.delete_role(:admin, context: project)
# List available roles within a specific context
Rabarber.roles(context: project)
```
--------------------------------
### Include Rabarber View Helpers
Source: https://context7.com/enjaku4/rabarber/llms.txt
This Ruby code snippet shows how to include Rabarber's view helpers within the ApplicationHelper module, making them available for use in Rails views.
```ruby
# app/helpers/application_helper.rb
module ApplicationHelper
include Rabarber::Helpers
end
```
--------------------------------
### Contextual Role Management - Ruby
Source: https://context7.com/enjaku4/rabarber/llms.txt
Provides methods for creating, renaming, deleting, and listing roles within specific contexts using the Rabarber gem. This allows for dynamic role management tied to particular resources or application areas. It also includes a 'prune' method to clean up orphaned roles.
```ruby
project = Project.find(10)
# Create a role within a context
Rabarber.create_role(:admin, context: Project)
# => true
Rabarber.create_role(:reviewer, context: project)
# => true
# List roles within specific contexts
Rabarber.roles(context: project)
# => [:reviewer]
Rabarber.roles(context: Project)
# => [:admin]
# Rename a role within a context
Rabarber.rename_role(:admin, :owner, context: project)
# => true
# Remove a contextual role
Rabarber.delete_role(:admin, context: project)
# => true
# Remove orphaned context roles (when context objects are deleted)
# This cleans up roles for deleted projects, companies, etc.
Rabarber.prune
```
--------------------------------
### Include Rabarber View Helpers in Rails Application
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Demonstrates how to include the Rabarber view helpers module within your Rails application's ApplicationHelper. This makes helper methods for conditional rendering available throughout your views.
```ruby
module ApplicationHelper
include Rabarber::Helpers
end
```
--------------------------------
### Assign and Query User Roles
Source: https://context7.com/enjaku4/rabarber/llms.txt
Manage user roles by assigning, checking, and revoking them. This includes assigning multiple roles, checking for specific roles, and retrieving all roles globally or contextually.
```ruby
# Get a user
user = User.find(1)
# Assign roles (creates roles if they don't exist)
user.assign_roles(:accountant, :manager)
# => [:accountant, :manager]
# Assign only existing roles (don't create new ones)
user.assign_roles(:admin, :supervisor, create_new: false)
# => [:accountant, :manager, :admin, :supervisor]
# Check if user has any of the specified roles
user.has_role?(:accountant, :manager)
# => true
user.has_role?(:guest)
# => false
# Get user's roles in the global context
user.roles
# => [:accountant, :manager, :admin, :supervisor]
# Get all user's roles grouped by context
user.all_roles
# => {nil=>[:accountant, :manager, :admin], Project=>[:owner], # => [:member]}
# Revoke specific roles
user.revoke_roles(:accountant, :manager)
# => [:admin, :supervisor]
# Revoke all roles
user.revoke_all_roles
# => []
```
--------------------------------
### Configure Rabarber Initialization
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Configures Rabarber settings such as role caching, the current user method, and the user model name within a Rails initializer.
```ruby
Rabarber.configure do |config|
config.cache_enabled = true # Enable/disable role caching (default: true)
config.current_user_method = :current_user # Method to access current user (default: :current_user)
config.user_model_name = "User" # User model name (default: "User")
end
```
--------------------------------
### Manage Contextual Roles Assignment and Revocation in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Shows how to assign, check, revoke, and retrieve user roles within specific contexts (e.g., models or classes) using `assign_roles`, `has_role?`, `revoke_roles`, and `roles` methods.
```ruby
# Assign roles within a specific model instance
user.assign_roles(:owner, context: project)
user.assign_roles(:member, context: project)
# Assign roles within a model class
user.assign_roles(:admin, context: Project)
# Check contextual roles
user.has_role?(:owner, context: project)
user.has_role?(:admin, context: Project)
# Revoke roles
user.revoke_roles(:owner, context: project)
# Get user roles
user.roles(context: Project)
# Get users with a role
User.with_role(:member, context: project)
```
--------------------------------
### Generate Rabarber Migration for Roles
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Generates a Rails migration to set up the database table for storing user roles. Supports both standard integer IDs and UUID primary keys.
```shell
# For standard integer IDs
rails generate rabarber:roles users
# For UUID primary keys
rails generate rabarber:roles users --uuid
```
--------------------------------
### Customize Unauthorized Access Handling in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Explains how to override the `when_unauthorized` method in `ApplicationController` to provide custom behavior when a user is denied access, such as returning a specific HTTP status.
```ruby
class ApplicationController < ActionController::Base
include Rabarber::Authorization
with_authorization
private
def when_unauthorized
head :not_found # Custom behavior to hide existence of protected resources
end
end
```
--------------------------------
### Manage Rabarber Roles
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Direct operations for creating, renaming, and deleting roles within the Rabarber system. Includes options to force operations even if roles are assigned.
```ruby
# Create a new role
Rabarber.create_role(:admin) # => true if created, false if already exists
# Rename a role
Rabarber.rename_role(:admin, :administrator) # => true if renamed, false if new name exists or role is assigned
Rabarber.rename_role(:admin, :administrator, force: true) # Force rename even if role is assigned
# Remove a role
Rabarber.delete_role(:admin) # => true if deleted, false if role is assigned
Rabarber.delete_role(:admin, force: true) # Force deletion even if role is assigned
# List available roles in the global context
Rabarber.roles
# List all available roles grouped by context
Rabarber.all_roles
```
--------------------------------
### Conditional Rendering with Rabarber View Helpers in ERB
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Illustrates using Rabarber's `visible_to` and `hidden_from` helpers in ERB templates for role-based and context-specific content display. These helpers allow developers to conditionally render HTML content based on user roles or object contexts.
```erb
<%= visible_to(:admin, :manager) do %>
<% end %>
<%= hidden_from(:guest) do %>
<% end %>
<%= visible_to(:owner, context: @project) do %>
<% end %>
```
--------------------------------
### Manage Roles via Rabarber API
Source: https://context7.com/enjaku4/rabarber/llms.txt
Create, rename, delete, and list roles using the Rabarber module methods. These operations allow for global management of roles within the application, with options for force operations and pruning orphaned roles.
```ruby
# Create a new role
Rabarber.create_role(:admin)
# => true (if created)
# => false (if already exists)
# List available roles in the global context
Rabarber.roles
# => [:admin, :manager, :accountant]
# List all available roles grouped by context
Rabarber.all_roles
# => {nil=>[:admin, :manager], "Project"=>[:owner, :member], "Company"=>[:admin]}
# Rename a role (fails if role is assigned to users or new name exists)
Rabarber.rename_role(:admin, :administrator)
# => true (if renamed)
# => false (if new name exists or role is assigned)
# Force rename even if role is assigned
Rabarber.rename_role(:admin, :administrator, force: true)
# => true
# Remove a role (fails if role is assigned)
Rabarber.delete_role(:admin)
# => true (if deleted)
# => false (if role is assigned)
# Force deletion even if role is assigned
Rabarber.delete_role(:admin, force: true)
# => true
# Remove orphaned context roles (when context objects are deleted)
Rabarber.prune
```
--------------------------------
### Clean Up Orphaned Context Roles in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Provides the `Rabarber.prune` command to remove authorization roles associated with deleted context objects, ensuring data integrity.
```ruby
Rabarber.prune
```
--------------------------------
### Enable Controller Authorization in Rails
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Includes the Rabarber authorization module in controllers to enforce role-based access control. Authorization can be enabled for all actions or selectively.
```ruby
class ApplicationController < ActionController::Base
include Rabarber::Authorization
with_authorization # Enable authorization for all actions
end
class InvoicesController < ApplicationController
with_authorization only: [:update, :destroy] # Selective authorization
end
```
--------------------------------
### Configure Rabarber Initialization
Source: https://context7.com/enjaku4/rabarber/llms.txt
Configure Rabarber by setting options such as cache_enabled, current_user_method, and user_model_name in an initializer file. You can also manually clear the role cache.
```ruby
# config/initializers/rabarber.rb
Rabarber.configure do |config|
config.cache_enabled = true # Enable/disable role caching (default: true)
config.current_user_method = :current_user # Method to access current user (default: :current_user)
config.user_model_name = "User" # User model name (default: "User")
end
# Clear the role cache manually if needed
Rabarber::Cache.clear
```
--------------------------------
### Assign and Revoke User Roles
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Methods to assign, revoke, and manage roles for a user model. Roles can be assigned individually or in batches, and existing roles can be enforced.
```ruby
# Assign roles (creates roles if they don't exist)
user.assign_roles(:accountant, :manager)
# Assign only existing roles
user.assign_roles(:accountant, :manager, create_new: false)
# Revoke specific roles
user.revoke_roles(:accountant, :manager)
# Revoke all roles
user.revoke_all_roles
```
--------------------------------
### Controller Access Rules with Rabarber
Source: https://context7.com/enjaku4/rabarber/llms.txt
Defines role-based access rules for controller actions using Rabarber's `grant_access` method. Rules can be applied controller-wide or to specific actions, supporting single or multiple roles. Unauthorized handling can be customized.
```ruby
# app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
# Controller-wide access
grant_access roles: :admin
# Action-specific access
grant_access action: :index, roles: [:manager, :support]
def index
# Accessible to admin, manager, and support roles
@tickets = Ticket.all
end
def destroy
# Accessible to admin role only (from controller-wide grant_access)
@ticket = Ticket.find(params[:id])
@ticket.destroy
end
end
# app/controllers/invoices_controller.rb
class InvoicesController < ApplicationController
# Multiple roles have access
grant_access roles: [:admin, :accountant, :manager]
def index
@invoices = Invoice.all
end
def show
@invoice = Invoice.find(params[:id])
end
end
```
--------------------------------
### Manage Authorization Contexts in Ruby
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Provides macros for renaming authorization contexts, useful when refactoring models (e.g., from 'Ticket' to 'Task'). It also offers functionality to remove orphaned context data when a model is entirely deleted.
```ruby
migrate_authorization_context!("Ticket", "Task")
delete_authorization_context!("Ticket")
```
--------------------------------
### Query Users by Roles using Scopes
Source: https://context7.com/enjaku4/rabarber/llms.txt
Utilize Active Record scopes provided by Rabarber to query users based on their assigned roles. This allows for efficient filtering of users by one or more roles, optionally within a specific context.
```ruby
# Find all users with admin or manager roles
User.with_role(:admin, :manager)
# => #, #]>
# Find users with a specific role in a context
User.with_role(:owner, context: project)
# => #]>
# Chain with other scopes
User.with_role(:admin).where(active: true).order(:created_at)
# => #, ...]>
```
--------------------------------
### Rename Ticket Table to Task
Source: https://context7.com/enjaku4/rabarber/llms.txt
This Ruby migration renames the 'tickets' database table to 'tasks' and migrates authorization contexts from 'Ticket' to 'Task'. The `down` method reverts the table rename.
```ruby
class RenameTicketToTask < ActiveRecord::Migration[7.1]
def up
# Rename your model table
rename_table :tickets, :tasks
# Migrate authorization context (irreversible)
migrate_authorization_context!("Ticket", "Task")
end
def down
rename_table :tasks, :tickets
# Context migration is irreversible
end
end
```
--------------------------------
### Unrestricted Controller Access with Rabarber
Source: https://context7.com/enjaku4/rabarber/llms.txt
Shows how to grant unrestricted access to all actions within a controller to any authenticated user by using `grant_access` without specifying roles. This is useful for public-facing or authenticated-only sections.
```ruby
# app/controllers/unrestricted_controller.rb
class UnrestrictedController < ApplicationController
# Allow all authenticated users to access all actions
grant_access
def index
# All authenticated users can access
end
def show
# All authenticated users can access
end
end
# app/controllers/mixed_controller.rb
class MixedController < ApplicationController
# Unrestricted index action
grant_access action: :index
def index
# Accessible to all authenticated users
@items = Item.all
end
# Restricted show action
grant_access action: :show, roles: :member
def show
# Accessible to members only
@item = Item.find(params[:id])
endend
```
--------------------------------
### Custom Unauthorized Handling in Rails with Rabarber
Source: https://context7.com/enjaku4/rabarber/llms.txt
Illustrates how to customize the behavior when a user is unauthorized in a Rails application using Rabarber. By overriding the `when_unauthorized` method, developers can control the response format (e.g., JSON for APIs or redirect for HTML).
```ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Rabarber::Authorization
with_authorization
private
def when_unauthorized
# Hide existence of protected resources
head :not_found
end
end
# app/controllers/api/base_controller.rb
class Api::BaseController < ApplicationController
private
def when_unauthorized
# Return JSON error for API
render json: { error: "Access denied" }, status: :forbidden
end
end
# Default behavior (if when_unauthorized not defined):
# - HTML format: redirect_back(fallback_location: root_path)
# - Other formats: head(:forbidden)
```
--------------------------------
### Remove Deprecated Ticket Model
Source: https://context7.com/enjaku4/rabarber/llms.txt
This Ruby migration removes the 'tickets' database table and deletes associated authorization context data for 'Ticket'. The `down` method is empty as context deletion is irreversible.
```ruby
class RemoveDeprecatedModel < ActiveRecord::Migration[7.1]
def up
# Remove your model table
drop_table :tickets
# Remove orphaned context data (irreversible)
delete_authorization_context!("Ticket")
end
def down
# Context deletion is irreversible
end
end
```
--------------------------------
### Skip Controller Authorization in Rails
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Allows selective skipping of Rabarber authorization for specific controller actions. This can be used to bypass authorization checks for certain endpoints.
```ruby
class TicketsController < ApplicationController
skip_authorization except: [:create, :update, :destroy]
end
```
--------------------------------
### Clear Rabarber Role Cache
Source: https://github.com/enjaku4/rabarber/blob/main/README.md
Manually clears the Rabarber role cache. This is useful if roles have been modified directly in the database.
```ruby
Rabarber::Cache.clear
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.