访问打包到Ruby Gem中的文件

v2g6jxz6  于 2023-03-17  发布在  Ruby
关注(0)|答案(2)|浏览(103)

我有一个Buildr扩展,我把它打包成一个gem。我有一个脚本集合,我想把它添加到一个包中。我将这些脚本存储为一个大的文本块,并将其写入文件。我希望拥有可以直接复制或读/写回的单独文件。我希望将这些文件打包到gem中。打包它们没有问题(只要把它们放在rake install之前的文件系统中)但是我不知道如何访问它们。有Gem Resources bundle类型的东西吗?

lrpiutwd

lrpiutwd1#

基本上有两种方法,
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 ... }
lf5gs5x2

lf5gs5x22#

下面是我使用Ruby 3.1.1所做的工作:

gem_path = Gem::Specification.find_by_name('gem_name').full_gem_path
js_path = File.join(gem_path, 'path/to/file/file.js')
js = File.read(js_path)

这甚至适用于gem_name中的代码。

相关问题