rails-conventions
Rails code patterns and conventions following rubocop-rails-omakase style.
What this skill does
# Rails Conventions
Opinionated Rails patterns for clean, maintainable code.
## Core Philosophy
1. **Duplication > Complexity**: Simple duplicated code beats complex DRY abstractions
- "I'd rather have four simple controllers than three complex ones"
2. **Testability = Quality**: If it's hard to test, structure needs refactoring
3. **Adding controllers is never bad. Making controllers complex IS bad.**
## Turbo Streams
Simple turbo streams MUST be inline in controllers:
```ruby
# FAIL: Separate .turbo_stream.erb files for simple operations
render "posts/update"
# PASS: Inline array
render turbo_stream: [
turbo_stream.replace("post_#{@post.id}", partial: "posts/post", locals: { post: @post }),
turbo_stream.remove("flash")
]
```
## Controller & Concerns
Business logic belongs in models or concerns, not controllers.
```ruby
# Concern structure
module Dispatchable
extend ActiveSupport::Concern
included do
scope :available, -> { where(status: "pending") }
end
class_methods do
def claim!(batch_size)
# class-level behavior
end
end
end
```
## Service Extraction
Extract when you see MULTIPLE of:
- Complex business rules (not just "it's long")
- Multiple models orchestrated
- External API interactions
- Reusable cross-controller logic
Service structure:
- Single public method
- Namespace by responsibility (`Extraction::RegexExtractor`)
- Constructor takes dependencies
- Return data structures, not domain objects
## Modern Ruby Style
```ruby
# Hash shorthand
{ id:, slug:, doc_type: kind }
# Safe navigation
created_at&.iso8601
@setting ||= SlugSetting.active.find_by!(slug:)
# Keyword arguments
def extract(document_type:, subject:, filename:)
def process!(strategy: nil)
```
## Enum Patterns
```ruby
# Frozen arrays with validation
STATUSES = %w[processed needs_review].freeze
enum :status, STATUSES.index_by(&:itself), validate: true
```
## Scope Patterns
```ruby
# Guard with .present?, chainable design
scope :by_slug, ->(slug) { where(slug:) if slug.present? }
scope :from_date, ->(date) { where(created_at: Date.parse(date).beginning_of_day..) if date.present? }
def self.filtered(params)
all.by_slug(params[:slug]).by_kind(params[:kind])
rescue ArgumentError
all
end
```
## Error Handling
```ruby
# Domain-specific errors
class InactiveSlug < StandardError; end
# Log with context, re-raise for upstream
def handle_exception!(error:)
log_error("Exception #{error.class}: #{error.message}", error:)
mark_failed!(error.message)
raise
end
```
## Testing (Minitest + Fixtures)
```ruby
test "describes expected behavior" do
email = emails(:two)
email.process
email.reload
assert_equal "finished", email.processing_status
end
```
Principles:
- **Behavior-driven**: Test what, not how
- **Fixture-based**: Use `emails(:two)` for setup
- **Mock externals**: Stub S3, APIs, PDFs
- **State verification**: `.reload` after operations
- **Helper methods**: `build_valid_email`, `with_stubbed_download`
## Naming (5-Second Rule)
If you can't understand in 5 seconds:
```ruby
# FAIL
show_in_frame
process_stuff
# PASS
fact_check_modal
_fact_frame
```
## JavaScript & Importmap
Rails 7+ uses importmap for JS dependency management. Scope dependencies to the narrowest entrypoint.
### Multiple Entrypoints
```ruby
# config/importmap.rb
pin "application" # Public entrypoint
pin "@hotwired/turbo-rails", to: "turbo.min.js"
pin "@hotwired/stimulus", to: "stimulus.min.js"
# Admin-only dependencies - pinned but only imported in admin entrypoint
pin "chartkick", to: "chartkick.js"
pin "Chart.bundle", to: "Chart.bundle.js"
```
```javascript
// app/javascript/application.js — public pages only
import "@hotwired/turbo-rails"
import "@hotwired/stimulus"
import "controllers"
// app/javascript/admin.js — imports public base + admin-only libs
import "application"
import "chartkick"
import "Chart.bundle"
```
```erb
<%# Admin layout %>
<%= javascript_importmap_tags("admin") %>
<%# All other layouts %>
<%= javascript_importmap_tags %>
```
### Adding New JS Dependencies
1. Determine scope: public-facing or admin-only?
2. Pin in `config/importmap.rb`
3. Import in the **correct** entrypoint
4. Never add admin-only libraries to `application.js`
## Performance
- Consider scale impact
- No premature caching
- KISS - Keep It Simple
- Indexes slow writes - add only when needed
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.