Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing files packaged into a Ruby Gem

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?

like image 903
Drew Avatar asked Oct 19 '11 21:10

Drew


1 Answers

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 ... }
like image 144
Alex Boisvert Avatar answered Nov 16 '22 00:11

Alex Boisvert