2011-10-19 38 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