9

我有一个构建器扩展,我将其打包为 gem。我有一组要添加到包中的脚本。目前,我将这些脚本存储为我正在写入文件的大文本块。我希望拥有可以直接复制或读/写回的单个文件。我希望将这些文件打包到 gem 中。我将它们打包没有问题(只需将它们粘贴在之前的文件系统中rake install),但我不知道如何访问它们。有宝石资源捆绑类型的东西吗?

4

1 回答 1

18

基本上有两种方式,

1) 您可以使用以下命令在 gem 中加载与 Ruby 文件相关的资源__FILE__

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 ... }
于 2011-10-20T04:28:16.693 回答