访问打包到Ruby Gem中的文件

Dre*_*rew 8 ruby gem packaging buildr

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

Ale*_*ert 17

基本上有两种方式,

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

def path_to_resources
  File.join(File.dirname(File.expand_path(__FILE__)), '../path/to/resources')
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

然后,

$LOAD_PATH.each { |dir|  ... look for resources relative to dir ... }
Run Code Online (Sandbox Code Playgroud)