Read more

Rails route namespacing (in different flavors)

Dominik Schöler
March 01, 2016Software engineer at makandra GmbH

TL;DR There are three dimensions you can control when scoping routes:

scope module: 'module', path: 'path', as: 'as' do
  resources :examples, only: :index
end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

→ Path Helpers: as_examples_path and as_examples_url
→ URLs: /path/examples
→ Controller module: Module::ExamplesController and views location: app/views/module/examples/

These options work with resources as well, e.g. resources :examples, path: 'demonstration'

namespace vs scope

The main difference between namespace and scope is:

  • namespace sets all three dimensions as default and you have to opt out any of the three dimensions for customization.
  • scope sets none of the three dimensions as default and you have to opt in any of the three dimensions for customization.

Examples

Changing URLs only

When you want to namespace some paths but leave the corresponding controllers and url helpers unaffected, you can use the scope method like follows:

scope path: 'proxy' do
  resources :properties
end
  • URL: /proxy/properties
  • Route helper: properties_path
  • Controller class: PropertiesController

A typical use case is the customer asking you to change some URLs.

Namespace controllers and path helpers without changing URLs

When you want to namespace your controller classes (group some controllers into a folder) but leave the corresponding routes unaffected, you can use the namespace method like follows:

namespace 'proxy', path: '/' do
  resources :properties
end
  • URL: /properties
  • Route helper: proxy_properties_path
  • Controller class: Proxy::PropertiesController

Without affecting path helpers

When you want to namespace some resources of your application, but keep plain route helpers, you can use the scope method like follows:

scope module: 'proxy', path: 'proxy' do
  resources :properties
end
  • URL: /proxy/properties
  • Route helper: properties_path
  • Controller class: Proxy::PropertiesController
Dominik Schöler
March 01, 2016Software engineer at makandra GmbH
Posted by Dominik Schöler to makandra dev (2016-03-01 12:02)