define-routes
Use this skill when defining routes in Hanami 2.x.
Core principle: Routes map URLs to Actions. They are explicit, readable, and RESTful.
Core Rules
Define routes in
config/routes.rb:# config/routes.rb module MyApp class Routes < Hanami::Routes root to: "home.index" get "/users", to: "users.index" get "/users/:id", to: "users.show" post "/users", to: "users.create" patch "/users/:id", to: "users.update" delete "/users/:id", to: "users.destroy" end endUse
resourcesfor RESTful routes:resources :users do resources :posts endGenerates:
GET /users→users.indexGET /users/:id→users.showPOST /users→users.createPATCH /users/:id→users.updateDELETE /users/:id→users.destroy
Use
resourcefor singular resources (no index):resource :profileName routes for URL generation:
get "/users", to: "users.index", as: :users get "/users/:id", to: "users.show", as: :userAccess in Views or Actions:
routes.path(:user, id: 1) # => "/users/1" routes.url(:users) # => "http://example.com/users"Scope routes for versioning or grouping:
scope "api" do scope "v1" do resources :users end endMount slices at paths:
slice :api, at: "/api" do resources :users endOrder matters: Hanami matches routes top-to-bottom. Put specific routes before general ones (wildcards):
# CORRECT: specific first get "/users/new", to: "users.new" get "/users/:id", to: "users.show"
Verifying Routes
After defining routes, inspect all registered routes with the Hanami CLI:
bundle exec hanami routes
This lists every route with its HTTP method, path, and action target. Use it to confirm routes are correctly registered before running tests or the server.
Common pitfalls:
- A route returning a 404 unexpectedly often means the corresponding Action file does not exist or its path doesn't match the
to:identifier. - If a more general route (e.g.
get "/users/:id") appears before a specific one (e.g.get "/users/new"), the specific route will never be reached — always check ordering withhanami routes. - Forgetting to restart the server after changing
config/routes.rbcan cause stale routing behaviour.
Integration
| Related Skill | When to chain |
|---|---|
| create-action | Routes point to Actions. Define routes after Actions exist. |
| create-slice | Slices can define their own routes. Understand slices before nesting routes. |
| write-request-spec (testing) | Test routes by making requests to them. |