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

Sunday, April 28, 2013

Rails Single Table Inheritance With ActiveAdmin and Namespaces

So I stumbled with this for hours, working on a monkey patch for Inherited Resources, finally giving up. Basically, if you use STI with ActiveAdmin, don't use module namespaces. It breaks the shit out of inherited resources.. IH can't deal with the "Name::Class" ::'s, it just borks.. the monkey patch I was working on was to resolve the error when IH tries to use the model name as an instance variable like @Name::Class, which ruby is not interested in trying to do.


So, moral of the story: Don't use namespaced (with modules) STI models with AA, or IH.
~Nic

UPDATE: I was sent this from an anonymous commenter.  Excellent tip:

This actually works if you create a dummy class for your Namespaced model. For example do something like this: ActiveAdmin.register Parent::Child, as "MyClass". And then create a dummy model called MyClass as class MyClass < Parent::Child. This works.
UPDATE: I was sent this as well by another commenter:
This ugly shit works:
ActiveAdmin.register ::MyModule::Base, :as => 'MyModel'


without Dummy models