Posted over 2 years ago. Visible to the public. Repeats.

Rails route namespacing (in different flavors)

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

Copy
scope module: 'module', path: 'path', as: 'as' do resources :examples, only: :index end

=> Path Helpers: as_examples_path and as_examples_url
=> URLs: /path/examples
=> Controller module: Module::ExamplesController and views location: app/views/module/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:

Copy
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 scope method like follows:

Copy
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:

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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
7 months ago
by Arne Hartherz
Keywords:
routes
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more