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?
Asked
Active
Viewed 4,955 times
9

Drew
- 15,158
- 17
- 68
- 77
2 Answers
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 = '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
and then,
$LOAD_PATH.each { |dir| ... look for resources relative to dir ... }

Alex Boisvert
- 2,850
- 2
- 19
- 18
-
Please use Gem.data_dir for finding the correct path. – ch2500 Nov 19 '16 at 16:02
-
@ch2500 Can you provide an example of using `Gem.data_dir`? – vtnate Aug 28 '20 at 19:10
0
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
.

Mike Slinn
- 7,705
- 5
- 51
- 85