Wednesday, August 28, 2013

Rails routing namespace removal, and avoiding catastrophe

So I am working on this project.  The project is one big application, with two sub applications.  One of the sub applications was axed in this context, but the other wasn't.  They had namespaces (say /first and /second)

it was requested to remove the namespace and put all of the controllers in the root namespace.

Panic ensued.

I came up with a quick solution, instead of re-writing a bunch of controllers, helpers JS and views:

Thankfully I had used path helpers in most cases, except javascript.  I went back, and put helpers in all of those places where I had been lazy, and used an actual path.  Then, when my routes file had

namespace :one do
  resources :things, :stuff
end

I changed it to (not inside any namespace)

scope module: 'one', as: 'one' do
  resources :things, :stuff
end

The module option sets the module prefix to be used in controllers (so I didn't have to change those), and the as option put the prefixes on the path helpers (so they'd still work even though it was all in root namespace).  

Upon further investigation, I found that the namespace route helper actually just uses scope like this


namespace :something do
  XYZ
end

converts to

scope module: :something, path: :something, as: :something do
  XYZ
end
So there.  If you ever need a wholesale change, you can drop the namespace helper in routes, and use scope to change the path without renaming a bunch of stuff. 

Hopefully this saves someone the headache I was looking at when the change was proposed.

~Nic