简体   繁体   中英

How to I get the controller_name of a subclassed controller from its parent?

I'm using some namespaced controllers that also inherit from a parent controller. In each subclass I need to have ( for anyone wondering why... ):

class Fruits::ApplesController < FruitsController
  # controller_name below is 'apples'
  require_dependency "fruits/#{controller_name}"
  ...
end

So, since I'd rather have the require_dependency line once in my parent class I tried to move it to FruitsController, but the problem is that controller_name is now equal to "fruits"..

class FruitsController < ApplicationController
  # controller_name is 'fruits' no matter which subclassed controller is called
  require_dependency "fruits/#{controller_name}"
  ...
end

So how can I properly get the value of the subclassed controller name in FruitsController, so that I can keep that require_dependency line out of my subclasses? controller_path doesn't help either.

Thanks!

As written, your "require_dependency" statement is only executed once, when the parent loads.

You could potentially use the Class#inherited method to require your dependency, like this (code untested).

class FruitsController < ApplicationController
  def self.inherited(subclass)
    subclass.require_dependency subclass.to_s.underscore
  end
end

The require statement above in the Fruits class is executed only once during the loading of the parent class, which means subclasses won't have it executed again. Check the following example:

class A
  puts name
end

class B < A
end
#=> A

So, you have to execute a separate require per subclass and thus you can't refactor it that way you want.

As I mentioned above in my response to @ElliotNelson (thanks a lot btw!), here's the code that I've placed in my FruitsController that has allowed me to re-factor my original code:

def self.inherited(subclass)    
  subclass.require_dependency subclass.controller_name
  super
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM