Object.const_get and Rails - cutting off parent module names

前端 未结 2 1990
一整个雨季
一整个雨季 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: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.

提交回复
热议问题