2012-04-12 76 views
17

有沒有辦法知道我的寶石的根路徑?我正嘗試從gem路徑中的yaml加載默認配置。如何用ruby獲取gem根目錄?尋找寶石根

回答

26

鑑於以下項目結構:

your_gem/ 
    lib/ 
    your_gem.rb 

這是我會怎麼做:

# your_gem.rb 

module YourGem 
    def self.root 
    File.expand_path '../..', __FILE__ 
    end 
end 

Ruby 2.0引入了Kernel#__dir__方法;它使一個相當短的解決方案:

# your_gem.rb 

module YourGem 
    def self.root 
    File.dirname __dir__ 
    end 
end 

如果您需要訪問其他目錄,你可以簡單地建立在root

module YourGem 
    def self.bin 
    File.join root, 'bin' 
    end 

    def self.lib 
    File.join root, 'lib' 
    end 
end 
+0

爲我引用我的「docs」文件夾作爲gemspec的一部分,其中使用默認的Rails.root.join(「docs」)失敗。謝謝! – 2014-03-05 15:56:36

+0

我使用ruby 2.0.0p0(2013-02-24修訂版39474)。 'File.dirname __dir__'不適合我。我得到這個錯誤:'TypeError:沒有將nil隱式轉換爲String'。發生瞭解爲什麼?謝謝。 – 2014-12-29 05:21:31

+0

@ EE33,['__dir__'被記錄爲返回'nil',如果'__FILE__'也是'nil'](http://www.ruby-doc.org/core-2.0.0/Kernel.html#method -i -__ dir__)。你如何運行你的腳本? – 2014-12-29 05:26:24

6

gem list <gem> -d

或者,如果你使用的捆綁:

bundle show <gem>

+0

在gem本身內:即時嘗試調用File.load。什麼是寶石根? – 2012-04-12 23:50:40

25

這是可執行文件和庫的通用解決方案。它使用Gem API加載規範,所以路徑始終是正確的:

spec = Gem::Specification.find_by_name("your_gem_name") 
gem_root = spec.gem_dir 
yaml_obj = YAML.load(gem_root + "/file_name.yaml") 
+2

使用['File.join'](http://www.ruby-doc.org/core-2.1 .1/File.html#method-c-join)而不是字符串連接。 – 2014-04-17 19:58:10

+0

@MatheusMoreira它爲什麼重要? – 2015-09-18 19:11:31

+1

'File.join'確保您爲您的操作系統使用適當的路徑分隔符,從而使代碼跨平臺「/」是針對linux的,Microsoft Windows的許多版本都使用「\」。 – 2016-05-18 21:05:15