从模块中获取类名 [英] Get class name from a module
问题描述
如何从模块中获取包含该模块的类的类名?
How I can get from a module the Class name of the class the module is included ?
module ActMethods
def some_method(*attr_names)
cls = self.class # this doesn't work
end
end
如何加载cls变量加载此模块的类的名称?
How I can get into the cls variable the name of the class to with this module is loaded ?
推荐答案
self.class
确实可以获得调用该方法的对象的类。假设模块包含在类中,这可以是包含模块或其子类的类。如果你真的只想要这个名字,你可以改用 self.class.name
。
self.class
does get you the class of the object the method is called on. Assuming the module was included into a class, this either is the class that included the module or a subclass thereof. If you really just want the name, you can use self.class.name
instead.
如果你扩展了带有模块的类,你想要获得该类,你可以只做 cls = self
(或 cls = name
如果你想把类的名字作为一个字符串)。
If you extended a class with the module and you want to get that class, you can just do cls = self
(or cls = name
if you want the name of the class as a string).
如果以上都没有帮助,你应该澄清你想要的。
If none of the above helps, you should clarify what you want.
这篇关于从模块中获取类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!