访问打包到Ruby Gem中的文件

我有一个Buildr扩展,我将其打包为gem.我有一组脚本要添加到包中.目前,我将这些脚本存储为我正在写入文件的大文本块.我希望有单独的文件,我可以直接复制或读/写回来.我希望将这些文件打包到gem中.我没有问题打包它们(只是在rake安装之前将它们粘贴在文件系统中)但我无法弄清楚如何访问它们.是否有Gem Resources捆绑类型的东西?
基本上有两种方式,

1)您可以使用__FILE__在gem中加载相对于Ruby文件的资源:

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

2)您可以将Gem中的任意路径添加到$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 = 'you@yourdomain.com'
  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 ... }
翻译自:https://stackoverflow.com/questions/7828066/accessing-files-packaged-into-a-ruby-gem

转载注明原文:访问打包到Ruby Gem中的文件