V1.3: Routing


Routing helpers are made of one public method (#routes), available for actions, views and templates. It’s a factory to generate relative or absolute URLs, starting from named routes.

For a given route named :home, we can use home_path or home_url to generate relative or absolute URLs, respectively.

Usage

Imagine we have the following routes for our application:

# apps/web/config/routes.rb
root        to: 'home#index'
get '/foo', to: 'foo#index'

resources :books

Relative URLs

We can do:

<ul>
  <li><a href="<%= routes.root_path %>">Home</a></li>
  <li><a href="<%= routes.books_path %>">Books</a></li>
</ul>

Which generates:

<ul>
  <li><a href="/">Home</a></li>
  <li><a href="/books">Books</a></li>
</ul>

We can’t link /foo, because it isn’t a named route (it lacks of the :as option).

Absolute URLs

module Web
  module Controllers
    module Books
      class Create
        include Web::Action

        def call(params)
          # ...
          redirect_to routes.book_url(id: book.id)
        end
      end
    end
  end
end

In the case above, we have passed a Hash as set of params that are required to generate the URL.

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