A.
文件 test_top_level.rb :
puts ' (in TestTopLevel ...)'
class TestTopLevel
end
使用 RSpec 测试文件 ttl.rb :
# This test ensures that an included module is always processed at the top level,
# even if the include statement is deep inside a nesting of classes/modules.
describe 'require inside nested classes/modules' do
# =======================================
it 'is always evaluated at the top level' do
module Inner
class Inner
require 'test_top_level'
end
end
if RUBY_VERSION[0..2] == '1.8'
then
Module.constants.should include('TestTopLevel')
else
Module.constants.should include(:TestTopLevel)
end
end
end
执行 :
$ rspec --format nested ttl.rb
require inside nested classes/modules
(in TestTopLevel ...)
is always evaluated at the top level
Finished in 0.0196 seconds
1 example, 0 failures
B.
如果不想处理不必要的 require 语句,可以使用 autoload 代替。autoload( name, file_name )
在第一次访问模块名称时注册要加载的文件名(使用 Object#require)。
文件 twitter_oauth.rb :
module TwitterOAuth
class Client
def initialize
puts "hello from #{self}"
end
end
end
文件 t.rb :
p Module.constants.sort.grep(/^T/)
class Foo
puts "in class #{self.name}"
autoload :TwitterOAuth, 'twitter_oauth'
def bar_2
puts 'in bar2'
TwitterOAuth::Client.new
end
end
temp = Foo.new
puts 'about to send bar_2'
temp.bar_2
p Module.constants.sort.grep(/^T/)
在 Ruby 1.8.6 中执行:
$ ruby -w t.rb
["TOPLEVEL_BINDING", "TRUE", "Thread", "ThreadError", "ThreadGroup", "Time", "TrueClass", "TypeError"]
in class Foo
about to send bar_2
in bar2
hello from #<TwitterOAuth::Client:0x10806d700>
["TOPLEVEL_BINDING", "TRUE", "Thread", "ThreadError", "ThreadGroup", "Time", "TrueClass", "TwitterOAuth", "TypeError"]