Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`autoload` raises an error but `require` does not (ruby)

Tags:

ruby

rubygems

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.

like image 216
Mark W Avatar asked Jun 23 '26 05:06

Mark W


1 Answers

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.

like image 179
Greg Campbell Avatar answered Jun 25 '26 01:06

Greg Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!