Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packaging a read-only data file with a Ruby gem

I'm working on a Ruby application that is deployed as a gem. I'd like to include a read-only data file with the gem and am not sure how/where that should be packaged

For a little background, this application deals with the MIDI spec which includes hundreds of constant values. For instance, controller "Channel Volume" is always identified by the value 7. "Sustain" is identified by 64. etc etc... In the past, people have included these values as a large set of constants in their code. That's fine but it seems more appropriate to me to include those in a language agnostic format such as yaml

Using the GEM_PATH to locate the yaml file is ugly and also wouldn't work when using the library in a non-gem deployment.

Thank you for your help

like image 458
Ari Russo Avatar asked May 25 '11 17:05

Ari Russo


4 Answers

If you place this file somewhere within the source tree of your Gem you can use a relative path to load it. From where you want to read it you can define the path like so: File.dirname(__FILE__) + "/here/is/my/file.txt"

You can use the path modifier .. like you would on the shell to go up a directory.

like image 21
Mark Avatar answered Nov 07 '22 15:11

Mark


The Rubygems package manager has its static files placed inside lib directory. For example, certificates (*.pem) are stored in lib/rubygems/ssl_certs. I believe they can be considered as the most authoritative source, thus I recommend you to do the same.

like image 118
skalee Avatar answered Nov 07 '22 15:11

skalee


I don't think RubyGems makes any assertions about where you should store files like this. I would put it under lib/ and do like @mkrmr says. I would use File.expand_path, though, because it's less typing and fixes some occasional problems with symlinks and moving files: YAML.load_file(File.expand_path('../../midi_codes.yml', __FILE__))

like image 35
Ian Avatar answered Nov 07 '22 16:11

Ian


There is a specified location for these files.

  1. Create a folder called <gemdir>/data in your gem
  2. Use the Gem.datadir method to locate this directory.

This appears to create a directory that is expected to be public.

If you want this file to be private,then using the File.dirname(__FILE__) + "/path" trick will accomplish that.

like image 34
Michael Bishop Avatar answered Nov 07 '22 17:11

Michael Bishop