tags:

views:

130

answers:

3

Is there an easy way, when running a Ruby script, to get it to automatically install gems required for script?

For example, consider these require statements at the top of a ruby script:

require 'net/http'
require 'fileutils'
require 'archive/zip'

Now, I know (as a human and programmer) that for this script to run on a given PC with Ruby, the 'gem install archive-zip' command needs to be run first, before the script will work. But if this script needs to run on dozens of PCs, is there anything that can save me from having to ensure ALL the gem dependancies are installed first?

Furthermore, what if there are several gems required?

A: 

Shoes has a really slick way of doing this. See this blog post by _why.

You could port some of that to standard ruby (without the fancy UI)

Sam Saffron
+1  A: 

By using gem unpack you can unpack the gems into a directory. From there, you can include them in your script. For example, randomly picking the gem morse (a gem that encodes/decodes morse code), let's say I use gem unpack morse to put it in a directory /gems/. It unpacks to the directory morse-0.0.2, since that's the version.

$LOAD_PATH << './gems/morse-0.0.2/lib'
require 'morse'
# The gem is included, and Morse is now defined.
Matchu
+1  A: 

Not sure if this is exactly what you are after but when I have a server set up how I want I dump a list of my gems to somewhere safe...

gem list > my_gems.txt

If I need to rebuild the box or build another machine I use this script to install the gems...

bulk_gems.rb
#! /usr/local/bin/ruby

STDIN.readlines.each do |l|
 m = l.match /^(\S+) \((.*)\)/
 unless m.nil?
   gem_name, versions = m[1], m[2].split(',')
   versions.each do |v|
     system "gem install #{gem_name} --version #{v} --ignore-dependencies"
   end
 end
end

more my_gems.txt | bulk_gems.rb
Henry
thats very close to what i am talking about. But what would the script look like if i WANTED the gem depenancies?
Ash
Just remove '--ignore dependencies'But if the list is your installed gem then you already have the dependencies so it's quicker not to worry about them.
Henry