I have the following code to pull out and instantiate Rails controllers:
def get_controller(route)
name = route.requirements[:controller]
return if name.nil?
if name.match(/\//)
controller_name = name.split('/').map(&:camelize).join('::')
else
controller_name = name.camelize
end
p controller_name: controller_name
controller = Object.const_get("#{controller_name}Controller")
p controller: controller
controller.new
end
some routes are single names - "users", "friends", "neighbors", "politicians", etc...
other routes are nested, such as "admin/pets", "admin/shopping_lists", "admin/users", etc...
The above code works (in that it properly builds and instantiates the controller) in most of the cases mentioned, except for one - in this example, "admin/users"
from the puts
statements, I'm getting the following:
{:controller_name=>"Admin::Users"}
{:controller => UsersController}
You'll notice that the namespace Admin
is getting cut off. My guess is that since this is only the case for controllers which share a name in multiple namespaces (users
and admin/users
), it has something do to with Rails autoloading (?). Any idea about what is causing this?
As per the comment from lx00st, I should also point out that I've tried various forms of getting these constants, another attempt was as follows:
sections = name.split('/')
sections.map(&:camelize).inject(Object) do |obj, const|
const += "Controller" if const == sections.last
obj.const_get(const)
end
The same problem was encountered with this approach.