tags:

views:

99

answers:

1

In my Ruby program, I'm trying to lazy-load a library (crack for the curious).

If I do this:

require 'rubygems'
require 'crack'

Everything is working fine. However, when I try this:

require 'rubygems'
autoload :Crack, 'crack'

A LoadError is raised. (no such file to load -- crack)

Why is this error being raised? Is it because 'crack' (and therefore my other user-installed gems) are not in my $LOAD_PATH?

edit:

Furthermore, autoload does work with the Standard Library:

autoload :Yaml, 'yaml'

works fine, and raises no errors.

+3  A: 

You'll need to add the 'crack' gem to your $LOAD_PATH by doing:

gem 'crack'

This is necessary because RubyGems replaces Kernel#require with a method that attempts to "activate" the gem before requiring it if necessary, but doesn't do the same thing for Kernel#load - and autoload calls load on the backend.

Greg Campbell
Excellent! Thanks for explaining Kernel#require, too! Do I need to place this before or after `require 'rubygems'` or does it matter?
Mark W
after: the "gem" method is added to Kernel by rubygems, so it's not going to be available until after rubygems has been required.
Greg Campbell