raffian
raffian

Reputation: 32066

How to install, require, and use a gem in ruby

I'm trying to use rake in my ruby script...(Ruby 1.8.6, JRuby 1.6.5)

Downloaded rake using gem install --remote rake, looks ok on install...

Fetching: rake-0.9.2.2.gem (100%)
Successfully installed rake-0.9.2.2
1 gem installed

I've got a simple ruby script which works fine, but when I import rake to using any of the following requires, it starts complaining....

require 'rake'
LoadError: no such file to load -- rake
  or
require '/lib/rake'
LoadError: no such file to load -- lib/rake

After some searching, I found that adding require 'rubygems' just before rakefixes the issue....

require 'rubygems'
require 'rake'

Even though it's working, I've got some questions...

  1. The gem spec on rake shows the require_path as lib, so why doesn't require '/lib/rake' work? Am I misunderstanding the significance of require_path?

  2. Why is it necessary to place require 'rubygems' before require 'rake'

Upvotes: 3

Views: 13725

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

Yes, you are misunderstanding the significance. The require_paths in the specification is an array of subdirectories of that gem's installation directory that should be searched for files belonging to the gem.

To find out where rake really is, try this:

 $ gem which rake

You'll see that it is actually installed somewhere completely unrelated to /lib; on my system, it's under /var/lib/gems. Ruby gems, in general, live in their own directory structure; the only file in the standard Ruby include path ($:) is rubygems itself, which you used to have to explicitly require in order to make any actual gems visible. (Since Ruby 1.9, that has not been necessary.)

Gems are more complex than just libraries to load; you can have multiple versions of the same gem installed, and specify which one you want at a time, and do other things that wouldn't work if the gems were just dumped into the standard Ruby include path.

Upvotes: 6

Vivien Barousse
Vivien Barousse

Reputation: 20875

  1. The require_path in the gemspec tells ruby where the files of this gem are located within the gem. It makes you able to type require 'rake', and ruby then knows it needs to look for /lib/rake within the gem installation folder.
  2. In Ruby 1.8, rubygems (the mechanism responsible for making gems available to your app) is not loaded by default, and the default ruby isn't aware of any gem on your system. You need to load rubygems before being able to require any other gem. This is not the case anymore with Ruby 1.9.

Upvotes: 1

Related Questions