/rails-cto:rails-cto-stimulusfrom rails-cto
Guides writing reusable Stimulus controllers for Rails 8/Hotwire projects. Covers naming conventions, wiring to ERB views, and integration with Turbo Streams/Frames.
Ships in rails-cto. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Before writing a new controller, search the existing controllers in app/javascript/controllers/ and app/components/ for one that already does what you need. Many behaviors are already covered — autosave, clipboard, redirect, sortable, hover toggling, reset form, and more live in utils/. Check index.js for the full inventory.
If no existing controller fits, design the new one for general-purpose reuse. Controllers should not be tightly coupled to a single view or feature. Keep behavior generic and configurable through values, targets, and action parameters so the same controller can be wired into different contexts without duplication. Place broadly reusable controllers in utils/; only use domain namespaces (posts/, feeds/) when the behavior is truly domain-specific.
Every Stimulus controller must be designed to work across multiple views and contexts. Ask: "Could another page need this same behavior?" If yes — and the answer is almost always yes — name and design it generically.
Name controllers after the behavior, not the feature:
| Task | WRONG (single-purpose) | RIGHT (reusable) |
|---|---|---|
| Save form when checkbox toggled | post_auto_check_controller.js | toggle_submit_controller.js |
| Dismiss a flash message | flash_close_controller.js | dismissable_controller.js |
| Copy text to clipboard on click | share_link_copy_controller.js | clipboard_controller.js |
| Show/hide a section | settings_panel_toggle_controller.js | toggle_element_controller.js |
| Submit form on input change | search_auto_submit_controller.js | auto_submit_controller.js |
| Confirm before destructive action | delete_post_confirm_controller.js | confirm_action_controller.js |
Drive specifics through values and targets, not hard-coded selectors:
// WRONG — hard-coded to one specific form
export default class extends Controller {
save() {
document.querySelector("#post-settings-form").requestSubmit();
}
}
// RIGHT — works with any form via targets
export default class extends Controller {
static targets = ["form"];
save() {
this.formTarget.requestSubmit();
}
}
If you find yourself including a feature name (post, user, feed, setting) in the controller filename, stop and rethink. The controller is probably too specific.
app/javascript/controllers/
├── index.js # All registrations live here
├── application_controller.js # Minimal base class
├── utils.js # Shared helper functions
├── transition.js # Reusable enter/leave transitions
│
├── <name>_controller.js # Root-level controllers
├── posts/ # Domain-namespaced controllers
├── users/
├── accounts/
├── stripe/
└── utils/ # Small, reusable utility controllers
app/components/**/ # ViewComponent controllers live with their components
Every controller is manually imported and registered in index.js.
There is no auto-loading — each new controller needs two lines added here.
// app/javascript/controllers/index.js
import AutosaveController from "./utils/autosave_controller";
application.register("utils--autosave", AutosaveController);
Naming rules for the identifier string:
| Controller location | Identifier pattern | Example |
|---|---|---|
utils/autosave_controller.js | utils--autosave | Double-dash separates namespace |
posts/list_reorder_controller.js | posts--list-reorder | Underscores become hyphens |
reader_controller.js (root) | reader | No namespace prefix |
app/components/overlays/modal_controller.js | overlays--modal | Components use their directory |
Follow this order inside every controller. See app/javascript/controllers/utils/autosave_controller.js as a compact reference:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
// 1. Static declarations — always at the top
static targets = ["form", "submit"];
static values = { delay: Number, refreshInterval: Number };
static outlets = []; // only if needed
static classes = []; // only if needed
// 2. Lifecycle hooks
connect() {
this.timeout = null;
this.duration = this.hasDelayValue ? this.delayValue : 1500;
}
disconnect() {
// Clean up listeners, timers, intervals
}
// 3. Public action methods (called from data-action)
save() { /* ... */ }
submit() { /* ... */ }
// 4. Private helpers (use # prefix)
#processResponse(html) { /* ... */ }
// 5. Private getters
get #csrfToken() {
return document.querySelector('meta[name="csrf-token"]')?.content;
}
}
Key conventions:
import { Controller } from "@hotwired/stimulus" — not ApplicationController, unless you specifically need its behaviorexport default class extends Controller (anonymous class)static targets, static values, etc. even if empty arrays aren't needed — only declare what you usehasXTarget / hasXValue guards before accessing optional targets/values/**
* Debounces form submissions to prevent duplicate saves
* when the user rapidly edits fields in the autosave form.
*/
save() { /* ... */ }
<%# Controller + values %>
<div data-controller="utils--autosave"
data-utils--autosave-delay-value="2000">
<%# Targets %>
<form data-utils--autosave-target="form">
<%# Actions — format: event->identifier#method %>
<input data-action="input->utils--autosave#save">
<button data-utils--autosave-target="submit">Save</button>
</form>
</div>
Multiple controllers on one element — space-separated:
<div data-controller="hover-toggler app--post">
Declare with types. Stimulus coerces automatically.
static values = {
url: String,
delay: Number,
open: Boolean,
items: Array,
config: Object,
// With defaults:
duration: { type: Number, default: 300 }
};
Use the *ValueChanged() callback to react to changes:
openValueChanged() {
this.applyVisibility();
}
Outlets — direct access to another controller instance:
static outlets = ["reader"];
summarize() {
this.readerOutlet.iframeTarget.classList.add("hidden");
}
<div data-controller="reader-summary"
data-reader-summary-reader-outlet="#reader-frame">
Custom events — loose coupling via document:
// Dispatch
document.dispatchEvent(new CustomEvent("post:drag-start", { detail: { id } }));
// Listen (bind in connect, remove in disconnect)
connect() {
this.onDragStart = this.#handleDragStart.bind(this);
document.addEventListener("post:drag-start", this.onDragStart);
}
disconnect() {
document.removeEventListener("post:drag-start", this.onDragStart);
}
Rendering Turbo Streams from JS:
const response = await fetch(url, {
method: "PATCH",
headers: {
"Accept": "text/vnd.turbo-stream.html",
"X-CSRF-Token": this.#csrfToken
}
});
const html = await response.text();
Turbo.renderStreamMessage(html);
Turbo Frame navigation:
this.frameTarget.src = newUrl;
Listening to Turbo events:
document.addEventListener("turbo:before-stream-render", this.#boundBeforeRender);
document.addEventListener("turbo:frame-load", () => { /* ... */ });
Always clean up in disconnect() to prevent memory leaks:
disconnect() {
clearTimeout(this.timeout);
clearInterval(this.interval);
document.removeEventListener("keydown", this.boundKeyHandler);
}
When binding listeners manually, store the bound reference so you can remove it:
connect() {
this.boundKeyHandler = this.#handleKey.bind(this);
document.addEventListener("keydown", this.boundKeyHandler);
}
Every controller that makes fetch requests uses this getter:
get #csrfToken() {
return document.querySelector('meta[name="csrf-token"]')?.content;
}
Use try-catch for fetch calls; fail silently for non-critical browser APIs:
async #loadContent() {
try {
const response = await fetch(this.urlValue);
if (!response.ok) throw new Error("Network response was not ok");
const html = await response.text();
this.contentTarget.innerHTML = html;
} catch (error) {
console.error("Failed to load content:", error);
}
}
The project provides transition.js for enter/leave animations:
import { transition } from "../transition";
async toggle() {
await transition(this.panelTarget, this.openValue);
}
For frame-perfect DOM updates, use double-rAF:
requestAnimationFrame(() => {
requestAnimationFrame(() => {
// DOM is fully painted before this runs
});
});
Before writing or running Stimulus controller tests, confirm the project has Vitest configured.
Check for Vitest in package.json:
grep -q '"vitest"' package.json && echo "vitest installed" || echo "vitest missing"
Check for a Vitest config file — look for vitest.config.js, vitest.config.ts, or a test section in vite.config.js:
ls vitest.config.* vite.config.* 2>/dev/null
Check the test script exists:
grep '"test"' package.json
If Vitest is not installed or configured, inform the user:
"This project doesn't have Vitest set up for JavaScript tests. To enable Stimulus controller testing, add these to your project:
yarn add -D vitest @testing-library/dom jsdomvitest.config.js:
import { defineConfig } from "vitest/config"; export default defineConfig({ test: { environment: "jsdom", globals: true, }, });package.json (add to scripts):
"test": "vitest run"Then run
yarn install."
If Vitest is not available, skip the testing sections below but still flag that tests are missing.
Every new or modified Stimulus controller must have a corresponding test file. Map by convention:
app/javascript/controllers/utils/autosave_controller.js → test/javascript/utils/autosave_controller.test.jsapp/javascript/controllers/posts/list_reorder_controller.js → test/javascript/posts/list_reorder_controller.test.jsapp/javascript/controllers/reader_controller.js → test/javascript/reader_controller.test.jsapp/components/overlays/modal_controller.js → test/javascript/components/overlays/modal_controller.test.jsIf the test file does not exist, create it.
import { Application } from "@hotwired/stimulus";
import AutosaveController from "controllers/utils/autosave_controller";
describe("AutosaveController", () => {
let application;
beforeEach(() => {
document.body.innerHTML = `
<div data-controller="utils--autosave"
data-utils--autosave-delay-value="500">
<form data-utils--autosave-target="form">
<input data-action="input->utils--autosave#save" />
<button data-utils--autosave-target="submit">Save</button>
</form>
</div>
`;
application = Application.start();
application.register("utils--autosave", AutosaveController);
});
afterEach(() => {
application.stop();
document.body.innerHTML = "";
});
it("connects the controller", () => {
const element = document.querySelector("[data-controller='utils--autosave']");
expect(element).not.toBeNull();
});
it("sets the delay value from the attribute", () => {
const controller = application.getControllerForElementAndIdentifier(
document.querySelector("[data-controller='utils--autosave']"),
"utils--autosave"
);
expect(controller.delayValue).toBe(500);
});
});
*ValueChanged callbacks firefetch and verify correct URL, method, headers, and response handlingyarn test # Full JS test suite
yarn test test/javascript/utils/autosave_controller.test.js # Single file
Always run yarn test after modifying any Stimulus controller. Tests must pass before the work is considered done.
When working on Stimulus controllers, also invoke /better-stimulus@obie-skills for additional best practices and patterns from betterstimulus.com. This skill complements the project-specific conventions above with broader community patterns for writing clean, maintainable Stimulus code.
utils/, app/components/, and index.js for something reusableapp/javascript/controllers/<namespace>/<name>_controller.jsapplication.register() to index.jsdata-controller="namespace--name"disconnect()#private methods for internal logicdata-action in HTML over manual addEventListener when possible.test.js file and run yarn testWhat SKILL.md sets; muted values are Claude Code's defaults
17 skills in this plugin
/rails-ctoOrchestrator skill for Ruby on Rails projects. Initializes sessions, routes to specialized skills, enforces mandatory QA gates, and runs the completion checklist. Invoke at the start of every Rails session./rails-cto-apiHow to build RESTful JSON APIs in a Rails 8 application following OpenAPI standards. Use when creating, modifying, or debugging API endpoints, serializers, authentication, documentation, or any code under the Api:: namespace. Also use when the user mentions "api", "endpoint", "api key", "serializer", "openapi", "swagger", "api documentation", "cors", "rate limit", "pagination cursor", "api versioning", or asks about exposing data to external consumers. Proactively apply these rules whenever touching API controllers, routes, or serializers, even if the user doesn't explicitly ask.
/rails-npx claudepluginhub mattsears/rails-cto --plugin rails-ctoOther plugins' skills for the same job