[英]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".. 所以,因为我宁愿在我的父类中使用require_dependency一行,我试图将它移动到FruitsController,但问题是controller_name现在等于“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? 那么如何在FruitsController中正确获取子类控制器名称的值,以便我可以将require_dependency行保留在子类之外? controller_path doesn't help either.
controller_path也无济于事。
Thanks! 谢谢!
As written, your "require_dependency" statement is only executed once, when the parent loads. 如上所述,您的“require_dependency”语句仅在父项加载时执行一次。
You could potentially use the Class#inherited method to require your dependency, like this (code untested). 你可能会使用Class#inherited方法来要求你的依赖,就像这样(代码未经测试)。
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. Fruits
类中的require语句在加载父类期间只执行一次,这意味着子类不会再次执行它。 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. 因此,您必须为每个子类执行单独的require,因此您无法以您想要的方式重构它。
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: 正如我在回复@ElliotNelson时提到的那样(非常感谢btw!),这里是我在
FruitsController
中放置的代码,它允许我重新考虑原始代码:
def self.inherited(subclass)
subclass.require_dependency subclass.controller_name
super
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.