I have the following code to pull out and instantiate Rails controllers:
def get_controller(route)
name = route.requirements[:controller]
return if name.nil?
This was solved by an answer from user apneadiving which can be found here
Be aware that there are vicious cases in Rails development mode. In order to gain speed, the strict minimum is loaded. Then Rails looks for classes definitions when needed.
But this sometimes fails big time example, when you have say
::User
already loaded, and then look for::Admin::User
. Rails would not look for it, it will think::User
does the trick.This can be solved using
require_dependency
statements in your code.
Personally I think this is a bug, not a feature, but...so it goes. It solves the problem.
First of all, this code is superfluous:
if name.match(/\//)
controller_name = name.split('/').map(&:camelize).join('::')
else
controller_name = name.camelize
end
The only string would perfectly handle both cases:
controller_name = name.split('/').map(&:camelize).join('::')
Then, you probably want to handle namespaces properly:
n_k = controller_name.split('::')
klazz = n_k.last
namespace_object = if n_k.length == 1
Object
else
Kernel.const_get(n_k[0..-2].join('::'))
end
controller = namespace_object.const_get("#{klazz}Controller")
Hope that helps.