require
class A
module C
class B
include C
end
在我的特定情况下,我有一组大量相互依赖的文件,以及一个加载这些文件的加载器。举个例子,我将把文件集简化为4个文件(a.rb、b.rb、c.rb和w.rb)。以下是这些文件的列表:
# In file a.rb
class A
@foo = []
@foo.push("in A")
def self.inherited(subclass)
foo = @foo.dup
subclass.instance_eval do
@foo = foo
end
end
def self.get_foo
@foo
end
end
# In file b.rb
class B < A
include C # if C is not already defined, the following line will not get executed although B will be defined.
@foo.push("in B")
end
# In file c.rb
module C
end
# In file w.rb
class W < B
@foo.push("in W")
end
# In file loader.rb
files = Dir["*.rb"].reject { |f| f =~ /loader/ }
files.sort! # just for the purpose of the example, to make them load in an order that causes the problem
files.reject! { |f| require(f) rescue nil } while files.size > 0
p W.get_foo
["in A", "in B", "in W"]
,这正是我想要的。
self.inherited
@foo
["in A", "in W"]
.
需要