好吧,我在加载一个或多个特定库时遇到了一些问题,即该库可能超出了范围。这是在这种情况下发生的事情吗?
主要问题:需要函数中的库,以便它们可以在全局范围内使用。 例如:
class Foo
def bar
require 'twitter_oauth'
#....
end
def bar_2
TwitterOAuth::Client.new(
:consumer_key => 'asdasdasd',
:consumer_secret => 'sadasdasdasdasd'
)
end
end
temp = Foo.new
temp.bar_2
现在解决我的问题我试图运行eval将它绑定到全局范围......就像这样
$Global_Binding = binding
class Foo
def bar
eval "require 'twitter_oauth'", $Global_Binding
#....
end
def bar_2
TwitterOAuth::Client.new(
:consumer_key => 'asdasdasd',
:consumer_secret => 'sadasdasdasdasd'
)
end
end
temp = Foo.new
temp.bar_2
但这似乎没有诀窍......任何想法?有没有更好的方法呢?
答案 0 :(得分:1)
:一种。强>
文件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
<强>乙强>
如果您不想处理不必要的require语句,则可以使用autoload。 autoload( name, file_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"]