我有一个模块(module A
(,它根据包含它的类的名称读取JSON文件(B.json
用于类B
,C.json
用于类C
等(,并为它们定义一些方法和常量。
我发现唯一可以访问类名的地方是self.included
方法,但我无法从它的外部访问它
我尝试了不同的方法,包括从self.included
或类的构造函数中设置实例变量,但没有成功。
以下是我的代码示例:https://replit.com/@EricNa1/CornyCruteredKeyboardmacro#main.rb
module A
puts "class name doesn't print here:", self.name
# I want to read a JSON file here based on the class name (e.g. B.json for B, C.json for C, etc.)
def self.included(clazz)
puts "but it prints here", clazz.name
end
end
class B
include A
end
class C
include A
end
B.new()
C.new()
打印
class name doesn't print here:
A
but it prints here
B
but it prints here
C
(我也不知道为什么"类名"不在这里打印:A只打印一次,尽管它应该从B调用一次,从C调用一次(
您的代码运行良好,它会打印:
class name doesn't print here:
A
不是因为包含了模块,而是因为创建了模块而打印。您可以对您的类进行评论,并看到该消息仍然打印出来。下一步,方法:
def self.included(clazz)
puts "but it prints here", clazz.name
end
当模块被包含在类中或某个地方时调用,类根本不调用它,因为类甚至没有访问该方法的权限,因为该方法带有"self",并且模块被包含,而不是扩展到类。因此,您可以用类似的东西获取包括该模块的所有类名:
module Super
@klass_names = []
def self.included(klass)
# puts "Class which included me " + klass.name
@klass_names << klass.name
end
def self.show_class_names
p @klass_names
end
end
class M
include Super
end
class B
include Super
end
Super.show_class_names
这个代码一点也不完美,但至少它给了你一个想法。