### Install Node Packages for Frontend Assets Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Adds necessary Node.js packages for frontend development, including Stimulus and Turbo for Hotwire, Bootstrap for UI components, Bootstrap Icons for iconography, and esbuild for efficient bundling. ```bash yarn add @hotwired/stimulus @hotwired/turbo-rails bootstrap bootstrap-icons esbuild sass ``` -------------------------------- ### Install Rails Gems for Asset Pipeline Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Installs essential gems for managing JavaScript, CSS, and asset handling within a Rails application. These gems facilitate the integration of modern front-end build tools and asset serving. ```ruby gem "cssbundling-rails" gem "jsbundling-rails" gem "propshaft" gem "stimulus-rails" gem "turbo-rails" ``` -------------------------------- ### Node.js Build and Watch Scripts (JSON) Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Defines scripts in `package.json` for building and watching front-end assets using esbuild and Sass. Supports both JavaScript and CSS build processes. ```json "scripts": { "build": "node esbuild.config.js", "build:css": "node node_modules/sass/sass.js ./app/assets/stylesheets/admin.scss:./app/assets/builds/admin.css ./app/assets/stylesheets/public.scss:./app/assets/builds/public.css --no-source-map --load-path=node_modules --style=compressed", "watch": "node esbuild.config.js --watch", "watch:css": "sass --watch ./app/assets/stylesheets/admin.scss:./app/assets/builds/admin.css ./app/assets/stylesheets/public.scss:./app/assets/builds/public.css --no-source-map --load-path=node_modules" } ``` -------------------------------- ### Foreman Development Process Config (Bash) Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Configures development processes for Foreman, including watching for JavaScript and CSS changes. Uses Yarn to execute build scripts. ```bash js: yarn build --watch css: yarn build:css --watch ``` -------------------------------- ### Stimulus Controller Setup Source: https://context7.com/wrburgess/optimus/llms.txt Initializes the Stimulus JavaScript application, enabling hot-reloading and integration with Turbo. Imports necessary modules like Turbo, Stimulus, Bootstrap, and local controllers. ```javascript // Stimulus setup - app/javascript/admin/index.js import "@hotwired/turbo-rails" import { Application } from "@hotwired/stimulus" const application = Application.start() application.debug = true window.Stimulus = application import "bootstrap" import "./controllers" ``` -------------------------------- ### Configure esbuild for Admin and Public JavaScript Bundles Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Sets up esbuild to bundle JavaScript files for both the admin and public sections of the application. It defines entry points, output files, and enables watch mode for development. ```javascript const path = require('path') const esbuild = require('esbuild') // Admin bundle esbuild.build({ entryPoints: ['app/javascript/admin/index.js'], bundle: true, outfile: 'app/assets/builds/admin.js', plugins: [], watch: process.argv.includes("--watch") }).catch(() => process.exit(1)) // Public bundle esbuild.build({ entryPoints: ['app/javascript/public/index.js'], bundle: true, outfile: 'app/assets/builds/public.js', plugins: [], watch: process.argv.includes("--watch") }).catch(() => process.exit(1)) ``` -------------------------------- ### CI Build Assets Step (YAML) Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Defines a step in a GitHub Actions CI workflow to build front-end assets. Executes `yarn build` and `yarn build:css` commands. ```yaml - name: Build assets run: | yarn build yarn build:css ``` -------------------------------- ### Public Layout View Config (Ruby) Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Includes JavaScript and CSS assets for the public layout in Rails applications. Uses `javascript_include_tag` and `stylesheet_link_tag` helpers. The 'public' JavaScript is deferred. ```ruby <%= javascript_include_tag "public", defer: true %> <%= stylesheet_link_tag "public" %> ``` -------------------------------- ### Import Bootstrap and Bootstrap Icons in SCSS Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Configures SCSS files to import Bootstrap styles and Bootstrap Icons. It also sets a custom path for Bootstrap Icon fonts to ensure they are loaded correctly. ```scss @use "bootstrap/scss/bootstrap"; @use "bootstrap-icons/font/bootstrap-icons"; $bootstrap-icons-font-src: url("bootstrap-icons.woff2") format("woff2"), url("fonts/bootstrap-icons.woff") format("woff") !default; // Your theme-specific styles here ``` -------------------------------- ### Admin Layout View Config (Ruby) Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Includes JavaScript and CSS assets for the admin layout in Rails applications. Uses `javascript_include_tag` and `stylesheet_link_tag` helpers. The 'admin' JavaScript is deferred. ```ruby <%= javascript_include_tag "admin", defer: true %> <%= stylesheet_link_tag "admin" %> ``` -------------------------------- ### Yarn Configuration for Node Linker Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Specifies the Node.js package manager configuration for Yarn, setting the linker to 'node-modules' and defining the path to the Yarn release executable. ```yaml nodeLinker: node-modules yarnPath: .yarn/releases/yarn-4.5.3.cjs ``` -------------------------------- ### Role-Based Access Control - Permission Checking (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code demonstrates how to check user permissions for specific resources and operations using a role-based access control system. It includes examples of direct permission checks, checking for any system permissions, and setting up user associations with groups and roles. ```ruby # Model: app/models/user.rb # Check if user has permission for a resource and operation user = User.find(123) # Direct permission check if user.access_authorized?(resource: 'users', operation: 'create') # User can create users end # Check if user has any system permissions if user.has_system_permission? # User has at least one permission end # User associations for RBAC # User -> SystemGroup -> SystemRole -> SystemPermission # Example: Assign user to groups with roles user = User.find(1) admin_group = SystemGroup.find_by(name: 'Administrators') SystemGroupUser.create!( system_group: admin_group, user: user ) # SystemPermission model structure # Attributes: name, resource, operation, abbreviation, description permission = SystemPermission.create!( name: 'Create Users', resource: 'users', operation: 'create', abbreviation: 'USR-C', description: 'Allows creating new users in the system' ) # SystemRole management role = SystemRole.create!(name: 'Admin', abbreviation: 'ADM') # Associate permission with role SystemRoleSystemPermission.create!( system_role: role, system_permission: permission ) # Associate role with group SystemGroupSystemRole.create!( system_group: admin_group, system_role: role ) ``` -------------------------------- ### GET /admin/users - List Users Source: https://context7.com/wrburgess/optimus/llms.txt Retrieves a paginated list of active users, with support for searching and sorting. ```APIDOC ## GET /admin/users ### Description Retrieves a paginated list of active users, with support for searching and sorting. ### Method GET ### Endpoint /admin/users ### Parameters #### Query Parameters - **q** (object) - Optional - Ransack search parameters. Example: `{"last_name_cont": "Smith"}`. - **page** (integer) - Optional - The page number for pagination. Defaults to 1. ### Request Example `GET /admin/users?q[last_name_cont]=Smith&page=2` ### Response #### Success Response (200 OK) - **pagy** (object) - Pagination information. - **instances** (array of objects) - A list of user objects. - **id** (integer) - User's unique identifier. - **first_name** (string) - User's first name. - **last_name** (string) - User's last name. - **email** (string) - User's email address. #### Response Example ```json { "pagy": { "page": 2, "items": 30, "pages": 5, "next": 3, "prev": 1, "from": 31, "to": 60, "count": 150, "metadata": {} }, "instances": [ { "id": 10, "first_name": "Jane", "last_name": "Doe", "email": "jane.doe@example.com" }, { "id": 11, "first_name": "John", "last_name": "Smith", "email": "john.smith@example.com" } ] } ``` ``` -------------------------------- ### Configure Rails to Include Node Modules Assets Source: https://github.com/wrburgess/optimus/blob/main/docs/asset_pipeline.md Updates the Rails asset configuration to include font assets from the Bootstrap Icons package, ensuring that icon fonts are correctly served by Propshaft. ```ruby Rails.application.config.assets.paths << Rails.root.join('node_modules/bootstrap-icons/font') ``` -------------------------------- ### ViewComponent Structure for Admin Interface (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code illustrates the structure for reusable UI components within the admin interface using the ViewComponent gem. It shows examples of component definitions for tables, form buttons, action buttons, headers, and dashboard cards. These components are designed to promote modularity and consistency in the admin panel's UI. ```ruby # app/components/admin/table_for_index/component.rb module Admin module TableForIndex class Component < ViewComponent::Base attr_reader :instances, :columns def initialize(instances:, columns:) @instances = instances @columns = columns end end end end # Usage examples in ERB: <%= render Admin::TableForIndex::Component.new( instances: @users, columns: [ { key: :full_name, label: 'Name' }, { key: :email, label: 'Email' }, { key: :created_at, label: 'Created' } ] ) %> <%= render Admin::FormButton::Component.new(label: 'Save User') %> <%= render Admin::ActionButton::Component.new( url: edit_admin_user_path(@user), label: 'Edit', variant: 'primary' ) %> <%= render Admin::HeaderForIndex::Component.new( title: 'Users', new_path: new_admin_user_path ) %> <%= render Admin::DashboardCard::Component.new( title: 'Total Users', value: User.count, icon: 'people' ) %> ``` -------------------------------- ### System Role and Permission Management (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code defines a SystemRole model with associations to system permissions and groups. It includes a method `update_associations` that manages these associations within a database transaction, ensuring data integrity. A usage example demonstrates how to update these associations. ```ruby # SystemRole model with associations class SystemRole < ApplicationRecord include Loggable validates :name, presence: true has_many :system_role_system_permissions, dependent: :destroy has_many :system_permissions, through: :system_role_system_permissions has_many :system_group_system_roles, dependent: :destroy has_many :system_groups, through: :system_group_system_roles has_many :users, through: :system_groups def update_associations(params) SystemRole.transaction do system_group_system_roles.delete_all if params[:system_role][:system_group_ids].present? params[:system_role][:system_group_ids]&.each do |system_group_id| SystemGroupSystemRole.create(system_role: self, system_group_id: system_group_id) end system_role_system_permissions.delete_all if params[:system_role][:system_permission_ids].present? params[:system_role][:system_permission_ids]&.each do |system_permission_id| SystemRoleSystemPermission.create(system_role: self, system_permission_id: system_permission_id) end end end end # Usage example role = SystemRole.find(1) role.update_associations( system_role: { system_group_ids: [1, 2, 3], system_permission_ids: [10, 11, 12] } ) ``` -------------------------------- ### Archivable Concern - Soft Delete Functionality (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This concern provides soft delete functionality for ActiveRecord models. It includes scopes for 'actives' and 'archives', and methods to check, archive, and unarchive records. Usage examples demonstrate its application in models and controllers. ```ruby # app/models/concerns/archivable.rb module Archivable extend ActiveSupport::Concern included do scope :actives, -> { where(archived_at: nil) } scope :archives, -> { where.not(archived_at: nil) } end def active? archived_at.blank? end def archived? archived_at.present? end def archive update(archived_at: DateTime.current) end def unarchive update(archived_at: nil) end end # Usage in models class User < ApplicationRecord include Archivable end # Query active users active_users = User.actives archived_users = User.archives # Archive a user user = User.find(1) user.archive # Check status user.archived? # => true user.active? # => false # Restore user user.unarchive # Admin controller archiving # PATCH /admin/users/:id/archive def archive @instance = @model_class.find(params[:id]) authorize(@instance) @instance.archive! @instance.log(user: current_user, operation: action_name) flash[:danger] = "User archived" redirect_to polymorphic_path([:admin, @model_class]) end # PATCH /admin/users/:id/unarchive def unarchive @instance = @model_class.find(params[:id]) authorize(@instance) @instance.unarchive! @instance.log(user: current_user, operation: action_name) flash[:success] = "User unarchived" redirect_to polymorphic_path([:admin, @instance]) end ``` -------------------------------- ### Loggable Concern - Audit Logging (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This concern enables automatic logging of CRUD operations using a background job. It associates logs with polymorphic models and includes methods for logging actions with optional notes and metadata. The DataLog model and query examples are also provided. ```ruby # app/models/concerns/loggable.rb module Loggable extend ActiveSupport::Concern included do has_many :data_logs, as: :loggable, dependent: :destroy end def log(user:, operation:, note: nil, meta: nil, original_data: nil) loggable_id = id loggable_type = self.class.name user_id = user.id CreateDataLogJob.perform_later( loggable_id: loggable_id, loggable_type: loggable_type, user_id: user_id, operation: operation, note: note, meta: meta, original_data: original_data ) end end # Usage in controllers def update instance = User.find(params[:id]) original_instance = instance.dup instance.update(update_params) instance.log( user: current_user, operation: action_name, meta: params.to_json, original_data: original_instance.attributes.to_json ) end # DataLog model class DataLog < ApplicationRecord belongs_to :loggable, polymorphic: true belongs_to :user def self.ransackable_attributes(*) %w[created_at id loggable_id loggable_type meta note operation original_data user_id] end end # Query logs # GET /admin/data_logs?q[loggable_type_eq]=User&q[operation_eq]=update logs = DataLog.where(loggable_type: 'User', operation: 'update') .includes(:user) .order(created_at: :desc) # Export logs to XLSX # GET /admin/data_logs/export_xlsx ``` -------------------------------- ### Admin User Creation with Auto Password and Confirmation (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code handles user creation through an admin interface. It automatically generates a password and its confirmation, sets the user as confirmed, logs the operation, and provides user feedback through flash messages before redirecting. ```ruby # POST /admin/users # Controller: app/controllers/admin/users_controller.rb # Form submission from admin interface # Automatic password generation and email confirmation def create temp_pw = SecureRandom.hex(16) params[:user][:password] = temp_pw params[:user][:password_confirmation] = temp_pw params[:user][:confirmed_at] = DateTime.current instance = controller_class.create(create_params) instance.log(user: current_user, operation: action_name, meta: params.to_json) flash[:success] = "New User successfully created" redirect_to polymorphic_path([:admin, instance]) end ``` -------------------------------- ### Admin User Index with Pagination and Search (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code snippet implements an index action for admin users. It utilizes Ransack for searching and sorting, and Pagy for pagination, allowing administrators to efficiently manage users. It also initializes a new user instance for potential form use. ```ruby # Admin index with pagination and search # GET /admin/users?q[last_name_cont]=Smith&page=2 def index @q = controller_class.actives.ransack(params[:q]) @q.sorts = ["last_name asc", "created_at desc"] if @q.sorts.empty? @pagy, @instances = pagy(@q.result) @instance = controller_class.new end ``` -------------------------------- ### User Creation via API Source: https://context7.com/wrburgess/optimus/llms.txt Create new users through the API. This endpoint automatically associates the new user with an organization and requires an Authorization header with a Bearer token. ```APIDOC ## POST /api/v1/users ### Description Create new users via the API. The system automatically associates the new user with an organization. Requires authentication. ### Method POST ### Endpoint /api/v1/users #### Request Body - **user** (object) - Required - Contains the user's details. - **email** (string) - Required - The user's email address. - **first_name** (string) - Required - The user's first name. - **last_name** (string) - Required - The user's last name. - **password** (string) - Required - The user's password. - **password_confirmation** (string) - Required - The user's password confirmation. ### Request Example ```json { "user": { "email": "jane.doe@example.com", "first_name": "Jane", "last_name": "Doe", "password": "SecurePassword123!", "password_confirmation": "SecurePassword123!" } } ``` ### Response #### Success Response (201 Created) - **id** (integer) - The unique identifier of the created user. - **email** (string) - The email address of the created user. - **first_name** (string) - The first name of the created user. - **last_name** (string) - The last name of the created user. - **created_at** (string) - The timestamp when the user was created in ISO 8601 format. #### Response Example ```json { "id": 42, "email": "jane.doe@example.com", "first_name": "Jane", "last_name": "Doe", "created_at": "2024-01-01T10:00:00Z" } ``` ``` -------------------------------- ### Create New User via API (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This controller action enables the creation of new users through an API endpoint. It handles user attributes including email, name, and password, and automatically associates the new user with an organization. It expects user attributes in the request body under the `user` key. ```ruby class Api::V1::UsersController < ApiController # ... other actions ... def create # Assuming user creation logic is handled here, potentially # including organization association based on context or parameters. # Example: # user = User.new(user_params) # if user.save # # Associate with organization logic # render json: user, status: :created, location: [:api, user] # else # render json: user.errors, status: :unprocessable_entity # end end private def user_params params.require(:user).permit(:email, :first_name, :last_name, :password, :password_confirmation) end # ... other actions ... end ``` -------------------------------- ### POST /admin/users - Create User Source: https://context7.com/wrburgess/optimus/llms.txt Creates a new user via the admin interface. If a password is not provided, a secure random password will be generated and confirmed. ```APIDOC ## POST /admin/users ### Description Creates a new user via the admin interface. If a password is not provided, a secure random password will be generated and confirmed. ### Method POST ### Endpoint /admin/users ### Parameters #### Query Parameters - **q** (object) - Optional - Ransack search parameters for filtering users. - **page** (integer) - Optional - Page number for pagination. #### Request Body - **user** (object) - Required - User details. - **email** (string) - Required - User's email address. - **password** (string) - Optional - User's password. If blank, it will be auto-generated. - **password_confirmation** (string) - Optional - Confirmation of the user's password. - **confirmed_at** (datetime) - Optional - Timestamp for user confirmation. ### Request Example ```json { "user": { "email": "newuser@example.com", "password": "securepassword123", "password_confirmation": "securepassword123" } } ``` ### Response #### Success Response (201 Created) - **id** (integer) - User's unique identifier. - **email** (string) - User's email address. #### Response Example ```json { "id": 1, "email": "newuser@example.com" } ``` #### Error Response (422 Unprocessable Entity) - **errors** (array of strings) - A list of validation errors. #### Error Response Example ```json { "errors": [ "Email has already been taken", "Password is too short (minimum is 8 characters)" ] } ``` ``` -------------------------------- ### Create User with Auto-Generated Password (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code snippet demonstrates the creation of a new user. If a password is not provided, it automatically generates a secure random password and confirms it. It also associates the new user with an organization and renders the user object or an error response. ```ruby def create authorize User user = User.new(user_params) # Generate secure random password if not provided if user_params[:password].blank? generated_password = SecureRandom.urlsafe_base64(16) user.password = generated_password user.password_confirmation = generated_password end if user.save # Associate user with the external application's organization OrganizationUser.create!( user: user, organization: @current_application.organization ) render json: user, status: :created else render json: { errors: user.errors.full_messages }, status: :unprocessable_entity end end ``` -------------------------------- ### package.json Scripts for Build and Watch Source: https://context7.com/wrburgess/optimus/llms.txt Defines npm scripts for building JavaScript and CSS assets, as well as watching for changes during development. Uses node to execute the esbuild config and sass for CSS. ```json { "scripts": { "build": "node esbuild.config.js", "build:css": "sass ./app/assets/stylesheets/admin.scss:./app/assets/builds/admin.css ./app/assets/stylesheets/public.scss:./app/assets/builds/public.css --no-source-map --load-path=node_modules --style=compressed", "watch": "node esbuild.config.js --watch", "watch:css": "sass --watch ./app/assets/stylesheets/admin.scss:./app/assets/builds/admin.css ./app/assets/stylesheets/public.scss:./app/assets/builds/public.css --no-source-map --load-path=node_modules" } } ``` -------------------------------- ### SCSS Configuration for Bootstrap and Icons Source: https://context7.com/wrburgess/optimus/llms.txt Configures SCSS imports for Bootstrap and Bootstrap Icons. Defines font source paths for Bootstrap Icons to ensure proper loading. ```scss // SCSS configuration - app/assets/stylesheets/admin.scss @use "bootstrap/scss/bootstrap"; @use "bootstrap-icons/font/bootstrap-icons"; $bootstrap-icons-font-src: url("bootstrap-icons.woff2") format("woff2"), url("fonts/bootstrap-icons.woff") format("woff") !default; ``` -------------------------------- ### esbuild Dual Bundle Configuration Source: https://context7.com/wrburgess/optimus/llms.txt Configures esbuild to create separate JavaScript bundles for the admin and public interfaces. Supports watch mode for development. The output files are placed in app/assets/builds. ```javascript // esbuild.config.js - Dual bundle configuration const path = require('path') const esbuild = require('esbuild') // Admin bundle esbuild.build({ entryPoints: ['app/javascript/admin/index.js'], bundle: true, outfile: 'app/assets/builds/admin.js', plugins: [], watch: process.argv.includes("--watch") }).catch(() => process.exit(1)) // Public bundle esbuild.build({ entryPoints: ['app/javascript/public/index.js'], bundle: true, outfile: 'app/assets/builds/public.js', plugins: [], watch: process.argv.includes("--watch") }).catch(() => process.exit(1)) ``` -------------------------------- ### Export Data to XLSX with Custom SQL (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code snippet demonstrates how to export data to an XLSX file format using custom SQL queries within a Rails controller. It fetches data using `ActiveRecord::Base.connection.select_all`, renders it using the `axlsx` gem via a template, and sends it as a file download. This functionality is typically used for reporting purposes in an admin interface. ```ruby def collection_export_xlsx sql = %( SELECT users.id AS id, users.first_name AS first_name, users.last_name AS last_name, users.email AS email, users.notes AS notes FROM users WHERE users.archived_at IS NULL ORDER BY users.last_name ASC ) @results = ActiveRecord::Base.connection.select_all(sql) file_name = controller_class_plural send_data( render_to_string( template: "admin/xlsx/reports", formats: [:xlsx], handlers: [:axlsx], layout: false ), filename: helpers.file_name_with_timestamp(file_name: file_name, file_extension: "xlsx"), type: Mime[:xlsx] ) end concern :collection_exportable do collection do get :export_xlsx, action: :collection_export_xlsx end end resources :users, concerns: :collection_exportable ``` -------------------------------- ### Foreman Procfile for Development Source: https://context7.com/wrburgess/optimus/llms.txt Defines process management commands for development using Foreman. Launches esbuild and Sass watchers for hot-reloading of JavaScript and CSS assets. ```plaintext // Development with Foreman - Procfile.dev.frontend js: yarn build --watch css: yarn build:css --watch ``` -------------------------------- ### User Management - List Users with Filtering Source: https://context7.com/wrburgess/optimus/llms.txt Query users with advanced filtering using Ransack and pagination with Pagy. Requires an Authorization header with a Bearer token. ```APIDOC ## GET /api/v1/users ### Description Query users with advanced filtering capabilities using Ransack and pagination with the Pagy gem. Requires authentication via JWT. ### Method GET ### Endpoint /api/v1/users #### Query Parameters - **q[email_cont]** (string) - Optional - Filters users whose email contains the specified string. - **q[s]** (string) - Optional - Sorts the results. For example, `name asc` or `last_name desc`. ### Request Example ```bash curl -X GET "https://example.com/api/v1/users?q[email_cont]=john&q[s]=name+asc" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -H "Content-Type: application/json" ``` ### Response #### Success Response (200 OK) - **(Array of User Objects)** - A list of user objects matching the query parameters. #### Response Example ```json [ { "id": 1, "email": "john.doe@example.com", "first_name": "John", "last_name": "Doe", "created_at": "2023-01-01T10:00:00Z", "updated_at": "2023-01-01T10:00:00Z" } ] ``` ``` -------------------------------- ### List Users with Filtering and Pagination (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This controller action allows fetching users with advanced filtering using Ransack and pagination via Pagy. It utilizes Pundit for policy scoping and returns a JSON array of user instances. It expects Ransack query parameters in `params[:q]`. ```ruby class Api::V1::UsersController < ApiController # ... other actions ... def index scoped_users = policy_scope(User) @q = scoped_users.ransack(params[:q]) @q.sorts = ["name asc", "created_at desc"] if @q.sorts.empty? @instances = @q.result render json: @instances end # ... other actions ... end class User < ApplicationRecord include Archivable include Loggable validates :email, presence: true, uniqueness: true devise :confirmable, :database_authenticatable, :lockable, :recoverable, :rememberable, :timeoutable, :trackable, :validatable has_many :system_group_users, dependent: :destroy has_many :system_groups, through: :system_group_users has_many :system_roles, through: :system_groups has_many :system_permissions, through: :system_roles scope :select_order, -> { order(last_name: :asc, first_name: :asc) } def self.ransackable_attributes(*) %w[archived_at email first_name id last_name updated_at] end def access_authorized?(resource:, operation:) system_permissions.where(resource: resource, operation: operation).exists? end end ``` -------------------------------- ### Copy System Permissions with Associations (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This Ruby code defines a `SystemPermission` model that can duplicate itself and trigger a background job to copy associated data. It is designed to be used within a Rails application. The `copy_with_associations` method duplicates the permission and then uses `DuplicateSystemPermissionAssociationsJob` to handle the associated data. ```ruby class SystemPermission < ApplicationRecord def copy_with_associations new_system_permission = dup new_system_permission.save DuplicateSystemPermissionAssociationsJob.perform_now(id, new_system_permission.id) new_system_permission end end # Example usage: permission = SystemPermission.find(5) new_permission = permission.copy_with_associations ``` -------------------------------- ### Generate API Token for User Authentication (Ruby) Source: https://context7.com/wrburgess/optimus/llms.txt This controller action generates JWT tokens for external applications to authenticate API requests. It uses `ExternalApplication` model for API key validation and `JsonWebTokenService` for token encoding. It expects `api_key` and `secret_key` in the request body. ```ruby class Api::V1::AuthenticationTokensController < ApiController skip_before_action :authorize_request, only: [:create] def create external_application = ExternalApplication.find_by(api_key: params[:api_key]) if external_application&.authenticate(params[:secret_key]) expiration_date = 24.hours.from_now token = JsonWebTokenService.encode( application_id: external_application.id, expiration_date: expiration_date ) render json: { token: token, exp: expiration_date.iso8601, application_name: external_application.name }, status: :ok else render json: { error: "unauthorized" }, status: :unauthorized end end end ``` -------------------------------- ### CSS for 404 Not Found Page Styling Source: https://github.com/wrburgess/optimus/blob/main/public/404.html This CSS code provides comprehensive styling for a 404 Not Found page. It includes responsive design elements, dark mode support, and specific styling for error messages and icons. It uses box-sizing, font-size clamping, and media queries for adaptive layouts. No external libraries are required. ```css *, *::before, *::after { box-sizing: border-box; } * { margin: 0; } html { font-size: 16px; } body { background: #FFF; color: #261B23; display: grid; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: clamp(1rem, 2.5vw, 2rem); -webkit-font-smoothing: antialiased; font-style: normal; font-weight: 400; letter-spacing: -0.0025em; line-height: 1.4; min-height: 100dvh; place-items: center; text-rendering: optimizeLegibility; -webkit-text-size-adjust: 100%; } #error-description { fill: #d30001; } #error-id { fill: #f0eff0; } @media (prefers-color-scheme: dark) { body { background: #101010; color: #e0e0e0; } #error-description { fill: #FF6161; } #error-id { fill: #2c2c2c; } } a { color: inherit; font-weight: 700; text-decoration: underline; text-underline-offset: 0.0925em; } b, strong { font-weight: 700; } i, em { font-style: italic; } main { display: grid; gap: 1em; padding: 2em; place-items: center; text-align: center; } main header { width: min(100%, 12em); } main header svg { height: auto; max-width: 100%; width: 100%; } main article { width: min(100%, 30em); } main article p { font-size: 75%; } main article br { display: none; @media(min-width: 48em) { display: inline; } } ``` -------------------------------- ### User Authorization Checks Source: https://context7.com/wrburgess/optimus/llms.txt Provides mechanisms for checking user permissions against specific resources and operations. ```APIDOC ## User Authorization Checks ### Description Provides mechanisms for checking user permissions against specific resources and operations, including direct checks and role-based access control. ### Methods #### `access_authorized?(resource:, operation:)` Checks if a user has a specific permission for a given resource and operation. #### `has_system_permission?` Checks if a user possesses any system-level permissions. ### Models and Associations - **User**: The primary user model. - **SystemGroup**: Represents a group of users. - **SystemRole**: Represents a role with associated permissions. - **SystemPermission**: Defines specific permissions (e.g., 'create users'). **Associations:** - User `belongs_to` SystemGroup (via `SystemGroupUser` join table) - SystemGroup `belongs_to` SystemRole (via `SystemGroupSystemRole` join table) - SystemRole `belongs_to` SystemPermission (via `SystemRoleSystemPermission` join table) ### Example Usage ```ruby # Check if user can create other users user = User.find(123) if user.access_authorized?(resource: 'users', operation: 'create') # User has permission end # Check if user has any system permissions if user.has_system_permission? # User has at least one permission end # Assign user to a group with a specific role user = User.find(1) admin_group = SystemGroup.find_by(name: 'Administrators') SystemGroupUser.create!(user: user, system_group: admin_group) # Define and assign permissions permission = SystemPermission.create!(name: 'Create Users', resource: 'users', operation: 'create') role = SystemRole.create!(name: 'Admin') SystemRoleSystemPermission.create!(system_role: role, system_permission: permission) SystemGroupSystemRole.create!(system_group: admin_group, system_role: role) ``` ``` -------------------------------- ### User Authentication - API Token Generation Source: https://context7.com/wrburgess/optimus/llms.txt Generate JWT tokens for external applications to authenticate API requests. This endpoint requires an API key and secret key for authentication. ```APIDOC ## POST /api/v1/authentication_tokens ### Description Generate JWT tokens for external applications to authenticate API requests. ### Method POST ### Endpoint /api/v1/authentication_tokens #### Request Body - **api_key** (string) - Required - The API key of the external application. - **secret_key** (string) - Required - The secret key of the external application. ### Request Example ```json { "api_key": "your_application_api_key", "secret_key": "your_application_secret" } ``` ### Response #### Success Response (200 OK) - **token** (string) - The generated JWT token. - **exp** (string) - The expiration date and time of the token in ISO 8601 format. - **application_name** (string) - The name of the authenticated application. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiJ9.eyJhcHBsaWNhdGlvbl9pZCI6MSwiZXhwIjoxNzA0MTIzNDU2fQ...", "exp": "2024-01-01T12:00:00Z", "application_name": "External App" } ``` #### Error Response (401 Unauthorized) - **error** (string) - Indicates that the authentication failed. #### Response Example ```json { "error": "unauthorized" } ``` ``` -------------------------------- ### TomSelect Stimulus Controller for Enhanced Select Inputs (JavaScript) Source: https://context7.com/wrburgess/optimus/llms.txt This JavaScript code implements a Stimulus controller that enhances standard HTML select elements using the TomSelect library. It provides features like search, multi-select, and tag creation. The controller connects to elements marked with `data-tom-select-target='tomselect'` and applies configurable settings. Dependencies include Stimulus and TomSelect. ```javascript import { Controller } from '@hotwired/stimulus' import TomSelect from 'tom-select' const selectSettings = { allowEmptyOption: true, plugins: ['remove_button', 'input_autogrow', 'clear_button'] } export default class extends Controller { static targets = ['tomselect'] connect() { this.tomselectTargets.forEach((element) => { new TomSelect(element, selectSettings) }) } } // Usage example in ERB: //