2011-10-19 70 views
8

我有一個Buildr擴展,我打包爲一個gem。我收集了一些我想添加到包中的腳本。目前,我將這些腳本存儲爲一個我要寫入文件的大文本塊。我寧願有個人文件,我可以直接複製或讀取/寫回。我希望將這些文件打包到寶石中。我沒有打包它們的問題(只需將它們粘貼到rake install之前的文件系統中),但我無法弄清楚如何訪問它們。是否有寶石資源捆綁類型的東西?訪問打包成Ruby Gem的文件

回答

16

基本上有兩種方式,

1)可以加載資源相對在你的寶石一個Ruby文件中使用__FILE__

def path_to_resources 
    File.join(File.dirname(File.expand_path(__FILE__)), '../path/to/resources') 
end 

2)您可以從寶石到添加任意路徑$LOAD_PATH變量,然後走$LOAD_PATH尋找資源,例如,

Gem::Specification.new do |spec| 
    spec.name = 'the-name-of-your-gem' 
    spec.version ='0.0.1' 

    # this is important - it specifies which files to include in the gem. 
    spec.files = Dir.glob("lib/**/*") + %w{History.txt Manifest.txt} + 
       Dir.glob("path/to/resources/**/*") 

    # If you have resources in other directories than 'lib' 
    spec.require_paths << 'path/to/resources' 

    # optional, but useful to your users 
    spec.summary = "A more longwinded description of your gem" 
    spec.author = 'Your Name' 
    spec.email = '[email protected]' 
    spec.homepage = 'http://www.yourpage.com' 

    # you did document with RDoc, right? 
    spec.has_rdoc = true 

    # if you have any dependencies on other gems, list them thusly 
    spec.add_dependency('hpricot') 
    spec.add_dependency('log4r', '>= 1.0.5') 
end 

然後,

$LOAD_PATH.each { |dir| ... look for resources relative to dir ... } 
+0

第一個人像一個魅力工作。 :) – Drew

+0

請使用Gem.data_dir查找正確的路徑。 – ch2500