From: David Masover Date: 2008-08-16T14:18:37+09:00 Subject: More autoload... No one had anything to say about this... Hmm. In case you didn't realize: I'm testing all of this in Ruby 1.9. I thought of a sneakier approach: The rdoc specifies that autoload will call Kernel::require: http://ruby-doc.org/core-1.9/classes/Kernel.html#M006100 And it does, indeed, seem to behave this way -- so long as I don't redefine Kernel::require. A simple test: $ irb1.9 irb(main):001:0> module Kernel irb(main):002:1> alias_method :require_without_me, :require irb(main):003:1> def require(*args, &block) irb(main):004:2> puts 'Require called:' irb(main):005:2> p args irb(main):006:2> p block irb(main):007:2> require_without_me *args, &block irb(main):008:2> end irb(main):009:1> end => nil irb(main):010:0> autoload :Foo, 'foo' => nil irb(main):011:0> Foo loaded foo.rb => Foo irb(main):012:0> require 'foo/bar' Require called: ["foo/bar"] nil loaded bar.rb => true irb(main):013:0> For what it's worth, both foo.rb and foo/bar.rb have 'puts' statements in them, declaring that they were loaded. Maybe it's irb at fault? Hmm... I created this file: module Kernel alias_method :require_without_me, :require def require(*args, &block) if args.first == 'test/file/not/loading' puts 'Not loading the test file' else require_without_me(*args, &block) end end end puts 'The following works:' require 'test/file/not/loading' puts 'The following does not:' autoload :Foo, 'test/file/not/loading' Foo I'd expect it to end with a constant not found, or module not found. Instead, I get: $ ruby1.9 test.rb The following works: Not loading the test file The following does not: test.rb:17:in `
': no such file to load -- test/file/not/loading (LoadError) Doesn't look like I typoed. So, in other words, autoload is either using its own interpretation of require, or it's hardcoding (in C) a call to the original require, rather than going through the Ruby code. (I wonder how this would have cooperated with Rubygems, had that not been included?) So far, the crushing limitation of autoload is that I can't easily autoload namespace'd things, without littering the namespace itself with autoload methods -- or eager-loading all parent namespaces. Well, that, and I can't seem to customize its behavior _at_all_ other than by rewriting it from scratch, making it somewhat useless.