Accessing files packaged into a Ruby Gem
Asked Answered
X

2

9

I have a Buildr extension that I'm packaging as a gem. I have a collection of scripts that I want to add to a package. Currently, I have these scripts stored as a big text block that I'm writing to file. I would prefer to have individual files that I can either copy directly or read/write back out. I would like these files to be packaged into the gem. I don't have a problem packaging them in (just stick them in the file system before rake install) but I can't figure out how to access them. Is there a Gem Resources bundle type thing?

Xiomaraxiong answered 19/10, 2011 at 21:1 Comment(0)
R
18

There are basically two ways,

1) You can load resources relative to a Ruby file in your gem using __FILE__:

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

2) You can add arbitrary paths from your Gem to the $LOAD_PATH variable and then walk the $LOAD_PATH to find resources, e.g.,

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

and then,

$LOAD_PATH.each { |dir|  ... look for resources relative to dir ... }
Romeo answered 20/10, 2011 at 4:28 Comment(2)
Please use Gem.data_dir for finding the correct path.Cattery
@Cattery Can you provide an example of using Gem.data_dir?Nineteenth
A
2

Here is what I did, using 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)

This even works for code within gem_name.

Actaeon answered 15/3, 2023 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.