Named Routes Create unique names for routes to be used in Hanami actions, views, and templates

Named Routes

We can specify a unique name for each route, in order to generate paths from the router or to test them. The unique name is assigned, using the :as option.

# apps/web/config/routes.rb

root              to: "home#index"
get "/hello",     to: "greet#index", as: :greeting
get "/books/:id", to: "books#show",  as: :book

When a Hanami application starts, it generates a Ruby module at the runtime under our application namespace: eg. Web.routes. We can use it to generate a relative or absolute URI for our route.

Web.routes.path(:root)     # => "/"
Web.routes.url(:root)      # => "http://localhost:2300/"

Web.routes.path(:greeting) # => "/hello"
Web.routes.url(:greeting)  # => "http://localhost:2300/hello"

When we have one or more variables, they can be specified as a Hash.

Web.routes.path(:book, id: 1) # => "/books/1"
Web.routes.url(:book, id: 1)  # => "http://localhost:2300/books/1"

Absolute URL generation is dependent on scheme, host and port settings in apps/web/application.rb.

Generating routes from Web.routes is helpful, because that module can be accessed from anywhere. However, this syntax is noisy.

Hanami has routing helpers available as routes in: actions, views, and templates.

<%= routes.path(:greeting) %>
<%= routes.url(:greeting) %>

Or

<%= routes.greeting_path %>
<%= routes.greeting_url %>

Learn more at Routing basig usage guide.

Twitter Facebook

Want to learn more about Hanami?

We have written an extensive Getting Started guide for curious people like you.