I have the following code to output 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, for example, "admin / pets", "admin / shopping_lists", "admin / users", etc.
The code above works (in that it correctly creates and creates an instance of the controller) in most of the cases mentioned, with the exception of one - in this example, "admin / users"
from puts statements, I get the following:
{:controller_name=>"Admin::Users"} {:controller => UsersController}
You will notice that the Admin namespace is being disabled. I assume that since this only applies to controllers that use the name in multiple namespaces ( users and admin/users ), it has something using Rails autoload (?). Any idea what causes this?
According to the comment from lx00st, I should also indicate that I have 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.
ruby ruby-on-rails
dax
source share