Rails Standards
by Convext
Ruby on Rails coding conventions and patterns
Rules (36)
Api
Follow REST conventions for predictable APIs: - GET /resources - List all - GET /resources/:id - Show one - POST /resources - Create - PUT/PATCH /resources/:id - Update - DELETE /resources/:id - Destroy Use nested routes for relationships: - GET /users/:user_id/orders - User's orders - POST /orders/:order_id/items - Add item to order Return appropriate HTTP status codes: - 200 OK, 201 Created, 204 No Content - 400 Bad Request, 401 Unauthorized, 404 Not Found - 500 Internal Server Error
Include version in your API URLs or headers: - URL versioning: `/api/v1/users` - Header versioning: `Accept: application/vnd.api+json; version=1` This allows you to: - Make breaking changes without affecting existing clients - Gradually migrate clients to new versions - Deprecate old versions with advance notice ```ruby # Rails routes namespace :api do namespace :v1 do resources :users end namespace :v2 do resources :users end end ```
Use a consistent error response format across all endpoints: ```json { "error": { "code": "validation_error", "message": "Validation failed", "details": [ { "field": "email", "message": "is invalid" }, { "field": "name", "message": "can't be blank" } ] } } ``` Include: - Machine-readable error code - Human-readable message - Field-level details for validation errors
Config
Follow 12-factor app principles for configuration: - Store config in environment variables, not in code - Use .env files for local development (never commit .env) - Commit .env.example with dummy values to document required variables - Never hardcode secrets, API keys, or connection strings This enables the same codebase to run in any environment.
Database
Encrypt or hash sensitive data: - Passwords: Use bcrypt (has_secure_password in Rails) - API keys: Encrypt with application-level encryption - PII: Consider field-level encryption - Never log sensitive data ```ruby class User < ApplicationRecord has_secure_password # Handles bcrypt hashing encrypts :ssn # Rails 7+ encryption end ```
Dependencies
When adding or updating dependencies, always use the latest stable version: - Check the official registry before adding (rubygems.org, npmjs.com, pypi.org) - Security vulnerabilities are fixed in newer versions - Performance improvements accumulate over time Do NOT use older versions. If the latest version has breaking changes, fix the code to work with the new API. Never assume migration is "too hard" without actually attempting the upgrade first.
Git
Make small, focused commits that do one thing well. Use Conventional Commits: - feat: new feature - fix: bug fix - refactor: code restructuring without behavior change - test: adding or updating tests - docs: documentation only - chore: maintenance tasks Example: `feat: add user authentication endpoint` Each commit should be independently deployable and revertible.
Llm Behavior
You are the only coder. Every line was written by you (this or previous sessions). There are no "pre-existing issues" - only issues you created and haven't fixed. Do not attribute problems to external sources or wait for someone else.
Prohibited excuses: "pre-existing", "unrelated errors", "would require refactoring", "tedious", "for now", "at this point", "tired", "frustrating", "time-consuming". These indicate you're making excuses. Recognize them and continue working.
You do not define success. The user and the test suite do. Do not redefine scope, declare victory on your terms, or summarize partial progress as completion. Done means: tests pass, linter passes, formatter run.
Rails
Use Rails built-in authentication (has_secure_password, authenticate_by) for all authentication logic. Never use Devise, Sorcery, Clearance, or similar authentication gems. Rails 8 provides everything needed: - has_secure_password for password hashing - authenticate_by for secure credential lookup - generates_token_for for password resets and email verification ```ruby class User < ApplicationRecord has_secure_password generates_token_for :password_reset, expires_in: 15.minutes end ```
Always use Strong Parameters to whitelist attributes: - Define permitted params in a private method - Never use `.permit!` which allows all attributes - Be explicit about nested attributes - Use `require` for the root key ```ruby private def user_params params.require(:user).permit(:name, :email, address_attributes: [:street, :city]) end ```
Don't rely solely on ActiveRecord validations - add database constraints: - NOT NULL for required fields - UNIQUE indexes for unique fields - Foreign key constraints for associations - Check constraints for business rules ```ruby # Migration add_column :users, :email, :string, null: false add_index :users, :email, unique: true add_foreign_key :orders, :users ``` Database constraints are your last line of defense against bad data.
Move slow operations to background jobs: - Email sending - File processing - External API calls - Report generation - Data imports/exports Use SolidQueue (Rails 8) or Sidekiq. Keep web requests under 200ms. ```ruby # Good: Background job SendWelcomeEmailJob.perform_later(user) # Bad: Synchronous in controller UserMailer.welcome(user).deliver_now ```
For Rails 7+ applications, prefer Hotwire (Turbo + Stimulus) over React/Vue: - Turbo Drive: Automatic AJAX page transitions - Turbo Frames: Partial page updates without JavaScript - Turbo Streams: Real-time updates over WebSocket - Stimulus: Lightweight JavaScript for sprinkles of behavior Only use a JavaScript framework when you need complex client-side state management (e.g., collaborative editing, complex forms, offline support).
Keep controllers thin - they should only: - Authenticate and authorize - Parse params and set instance variables - Call model/service methods - Render response Business logic belongs in: - Models (for single-model operations) - Service objects (for multi-model operations) - Form objects (for complex form handling) - Query objects (for complex queries) ```ruby # Good: Thin controller def create @order = OrderCreator.new(order_params, current_user).call respond_with @order end ```
Use Minitest for all tests. Do not add RSpec to the project. Minitest is: - Rails default, zero configuration - Faster boot time - Simpler syntax, less magic - Already integrated with fixtures ```ruby class UserTest < ActiveSupport::TestCase test "validates email presence" do user = User.new(name: "Test") assert_not user.valid? assert_includes user.errors[:email], "can't be blank" end end ``` Use fixtures for test data - they're fast and simple.
Use eager loading to prevent N+1 queries: - `includes`: For associations you'll access - `preload`: Force separate queries (useful for complex conditions) - `eager_load`: Force LEFT OUTER JOIN Use the Bullet gem in development to detect N+1 queries automatically. ```ruby # Bad: N+1 queries @posts = Post.all @posts.each { |p| p.author.name } # Queries author for each post # Good: Eager loading @posts = Post.includes(:author) @posts.each { |p| p.author.name } # Single query for authors ```
Define scopes for frequently used query conditions: - Makes code more readable - Enables method chaining - Centralizes query logic - Easier to test ```ruby class Order < ApplicationRecord scope :recent, -> { where('created_at > ?', 1.week.ago) } scope :completed, -> { where(status: 'completed') } scope :for_user, ->(user) { where(user: user) } end # Usage Order.recent.completed.for_user(current_user) ```
Always use `has_many :through` instead of `has_and_belongs_to_many`: - Allows adding attributes to the join model - Provides a model for the join table (validations, callbacks) - More flexible for future requirements - Easier to query and understand ```ruby # Good class User < ApplicationRecord has_many :memberships has_many :teams, through: :memberships end # Avoid class User < ApplicationRecord has_and_belongs_to_many :teams end ```
Ruby
In Ruby, favor composition and modules over deep inheritance hierarchies: - Use modules for shared behavior (concerns in Rails) - Inject dependencies rather than inheriting from base classes - Keep inheritance depth to 2-3 levels maximum - Use duck typing - if it quacks like a duck, treat it like a duck ```ruby # Good: Composition class OrderProcessor def initialize(payment_gateway:, notifier:) @payment_gateway = payment_gateway @notifier = notifier end end # Avoid: Deep inheritance class SpecialOrderProcessor < OrderProcessor < BaseProcessor < ApplicationService ```
Add `# frozen_string_literal: true` to the top of Ruby files: - Prevents accidental string mutation - Improves memory usage and performance - Catches bugs where strings are mutated unexpectedly Configure RuboCop to enforce this automatically.
Leverage modern Ruby features for cleaner code: - Pattern matching: `case obj in { name:, age: } then ...` - Endless methods: `def square(x) = x * x` - Hash shorthand: `{ x:, y: }` instead of `{ x: x, y: y }` - Numbered block parameters: `array.map { _1 * 2 }` - Data classes for simple value objects Keep Ruby version at 3.2+ for best performance and features.
Be intentional about method return values: - Methods that perform actions should return meaningful results or self - Query methods should return the queried value - Predicate methods (ending in ?) should return true/false - Bang methods (ending in !) should modify in place or raise ```ruby # Good: Clear intent def process_order validate! charge_payment send_confirmation self # Allow chaining end # Good: Predicate returns boolean def valid? = errors.empty? ```
Security
Force HTTPS for all traffic: - Configure SSL/TLS in production - Redirect HTTP to HTTPS - Use secure cookies (Secure, HttpOnly, SameSite) - Set HSTS headers ```ruby # Rails config/environments/production.rb config.force_ssl = true config.ssl_options = { hsts: { expires: 1.year, subdomains: true } } ```
Never trust user input - validate and sanitize everything: - Use allowlists, not denylists - Validate type, length, format, and range - Sanitize HTML to prevent XSS - Use parameterized queries to prevent SQL injection ```ruby # Rails automatically escapes in views, but be explicit with user HTML: sanitize(user_content, tags: %w[p br strong em]) # Always use parameterized queries (ActiveRecord does this by default): User.where(email: params[:email]) # Safe User.where("email = '#{params[:email]}'") # DANGEROUS - SQL injection ```
Testing
Separate authentication (who are you?) from authorization (what can you do?): Authentication: - Use secure password hashing (bcrypt) - Implement rate limiting on login - Use secure session management - Consider MFA for sensitive applications Authorization: - Check permissions on every request - Use policy objects or authorization gems (Pundit, CanCanCan) - Never rely on client-side checks alone ```ruby # Pundit example def update @post = Post.find(params[:id]) authorize @post # Raises unless user can update @post.update!(post_params) end ```
If you encounter a test failure, do not ignore it or mark it as skipped. - Investigate the root cause immediately - If it's a real bug, fix it before proceeding - If it's a flaky test, fix the flakiness - Never wave off failures as "pre-existing" - own the codebase state A test suite with skipped or ignored tests is a test suite you can't trust.
When writing unit tests, never mock the class you are testing. You should test the real instance of the class to ensure it behaves correctly. Mocking the class under test defeats the purpose of the test and can hide bugs.
Avoid mocking internal code or private methods. Mocks should be used only at system boundaries: - External HTTP APIs (use WebMock, VCR, or similar) - Time-dependent code (freeze time with travel_to) - File system operations that would persist outside tmp/ or create side effects - Third-party services with rate limits or costs Internal services, database operations, and business logic should use real implementations to ensure proper integration.
Follow Test-Driven Development for new features and bug fixes: 1. RED: Write a failing test that defines the expected behavior 2. GREEN: Write the minimum code to make the test pass 3. REFACTOR: Clean up the code while keeping tests green This ensures every line of code has a reason to exist and is tested.
Write tests that verify behavior, not internal implementation: - Test public interfaces, not private methods - Focus on inputs and outputs - Tests should survive refactoring - If implementation changes but behavior doesn't, tests should pass ```ruby # Good: Test behavior test "order total includes tax" do order = Order.new(items: [Item.new(price: 100)]) assert_equal 108, order.total # 8% tax end # Bad: Test implementation test "order calls calculate_tax method" do order = Order.new(items: [Item.new(price: 100)]) assert order.instance_variable_get(:@tax_calculated) end ```
Each test should verify one logical concept: - Multiple assertions are fine if they test the same thing - Separate tests for separate behaviors - Clear test names that describe the behavior ```ruby # Good: One concept test "user is invalid without email" do user = User.new(name: "Test") assert_not user.valid? assert_includes user.errors[:email], "can't be blank" end # Bad: Multiple concepts test "user validation" do user = User.new assert_not user.valid? # Missing everything user.email = "[email protected]" assert_not user.valid? # Missing name user.name = "Test" assert user.valid? # Now valid end ```
Use fixtures for consistent test data. Fixtures are: - Fast: loaded at database level, not through ActiveRecord - Simple: YAML files, no DSL to learn - Stable: good for reference data that rarely changes ```ruby # test/fixtures/users.yml admin: name: Admin User email: [email protected] role: admin regular: name: Regular User email: [email protected] role: member ``` Reference in tests with `users(:admin)`.
Workflow
Ensure your changes work on your local machine before pushing: - Run the application and manually verify changes - Run the full test suite - Check for console errors or warnings CI is for catching environment-specific issues, not basic functionality.
Before every commit, run the full quality pipeline: 1. Format code (prettier, black, rubocop --autocorrect, etc.) 2. Run linter (eslint, pylint, rubocop, etc.) 3. Run full test suite Never rely on CI to catch issues you could have caught locally. Configure pre-commit hooks to enforce this automatically.
Language Standards (1)
Use this Ruleset
Sign in to adopt or fork this ruleset
Sign in with GitHubStatistics
- Rules
- 36
- Standards
- 1
- Projects using
- 1
- Created
- Nov 28, 2025