如何包含动态ruby文件

时间:2013-02-04 17:12:49

标签: ruby

我想将所有ruby文件包含在实现函数toto()的目录中。

在python中我会这样做:

res = []
for f in glob.glob("*.py"):
  i = __import__(f)
  if "toto" in dir(i):
    res.append(i.toto)

我可以像这样使用这个列表:

for toto in res:
  toto()

1 个答案:

答案 0 :(得分:2)

在Ruby中,导入与Python非常不同 - 在Python文件和模块中或多或少是相同的东西,在Ruby中它们不是。您必须手动创建模块:

res = []
Dir.glob("*.rb") do |file|
  # Construct a class based on what is in the file,
  # and create an instance of it
  mod = Class.new do
    class_eval File.read file
  end.new

  # Check if it has the toto method
  if mod.respond_to? :toto
    res << mod
  end
end

# And call it
res.each do |mod|
  mod.toto
end

或许更多Ruby惯用语:

res = Dir.glob("*.rb").map do |file|
  # Convert to an object based on the file
  Class.new do
    class_eval File.read file
  end.new
end.select do |mod|
  # Choose the ones that have a toto method
  mod.respond_to? :toto
end

# Later, call them:
res.each &:toto