2010-08-05 42 views
2

我有一个模块和一个包含该模块的类。这些没有在相同的文件或相同的文件夹中定义。我希望模块得到这个类中定义的目录ruby​​模块是否可以获取定义包含该模块的类的文件的目录?

# ./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: ../

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

回答

2

类可以在许多文件中定义,所以你的问题没有真正的答案。在另一方面,你能分辨出哪个文件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,require 'backports'或将partition更改为其他内容。

+0

谢谢!这对我来说是获得我想要的功能的好方法。我担心多文件问题。知道包括什么是我需要的。 :) – 2010-08-06 00:45:41

0

这是做你想做的吗?

module Foo 
    def self.included(obj) 
    obj_dirname = File.expand_path(File.dirname($0)) 
    puts "the class that included Foo was defined in this directory: #{obj_dirname}" 
    end 
end 

编辑:根据意见更改。

+0

没有。返回“./modules/foo.rb” – 2010-08-05 20:44:34

+0

是的,对不起。将'__FILE__'替换为'$ 0'。 〜/ tmp/modules中的bar.rb和〜/ tmp/modules中的foo.rb是运行bar.rb时的输出:“包含Foo的类在此目录中定义:/ Users/xxx/tmp” – 2010-08-06 06:38:16

2

有没有内置的方法来找出模块或类的定义(afaik)。在Ruby中,您可以随时在任何地方重新打开模块/类并添加或更改行为。这意味着,通常没有一个单独的地方可以定义模块/类,而这样的方法是没有意义的。

但是,在您的应用程序中,您可以坚持一些约定,以便能够构造源文件名。例如。在Rails中,页面控制器通常被命名为PagesController,并且主要在文件app/controllers/pages_controller.rb中定义。

0
module Foo 

    def self.included obj 
    filename = obj.instance_eval '__FILE__' 
    dirname = File.expand_path(File.dirname(filename)) 
    puts "the class that included Foo was defined in this directory: #{dirname}" 
    end 

end 
+0

这是行不通的。 '__FILE__'不是一个方法,'instance_eval'返回'“(eval)”' – 2010-08-06 02:31:54

相关问题