gpt4 book ai didi

ruby - ruby 模块是否有可能获取定义包含该模块的类的文件的目录?

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:14 27 4
gpt4 key购买 nike

我有一个模块和一个包含该模块的类。这些不是在同一个文件或同一个文件夹中定义的。我希望模块获取定义该类的目录。

# ./modules/foo.rb
module Foo
def self.included(obj)
obj_dirname = # ??? what goes here?
puts "the class that included Foo was defined in this directory: #{obj_dirname}"
end
end

# ./bar.rb
class Bar
include Foo
end

我希望它的输出是:

the class that included Foo was defined in this directory: ../

这可能吗?如果是,怎么办?

最佳答案

类可以在很多文件中定义,所以你的问题没有真正的答案。另一方面,您可以判断 include Foo 是从哪个文件生成的:

# ./modules/foo.rb
module Foo
def self.included(obj)
path, = caller[0].partition(":")
puts "the module Foo was included from this file: #{path}"
end
end

这将是您正在寻找的路径,除非在其他地方有 MyClass.send :include, Foo 然后定义了 MyClass...

注意:对于 Ruby 1.8.6,需要“向后移植” 或将分区 更改为其他内容。

关于ruby - ruby 模块是否有可能获取定义包含该模块的类的文件的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3416869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com