2010-08-05 55 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

相關問題