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

非 Y 不嫁゛ 提交于 2019-12-21 20:35:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/849622/autoload-raises-an-error-but-require-does-not-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!