Object.const_get and Rails - cutting off parent module names

前端 未结 2 1970
一整个雨季
一整个雨季 2021-01-25 03:51

I have the following code to pull out and instantiate Rails controllers:

def get_controller(route)
  name = route.requirements[:controller]
  return if name.nil?         


        
相关标签:
2条回答
  • 2021-01-25 04:25

    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.

    0 讨论(0)
  • 2021-01-25 04:36

    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.

    0 讨论(0)
提交回复
热议问题