1

好的,我在加载特定库或更多库可能超出范围时遇到了一些麻烦。这就是在这种情况下发生的事情吗?

主要问题:需要函数中的库,以便它们可以在全局范围内使用。例子:

   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

但这似乎并没有奏效……有什么想法吗?有没有更好的方法来做到这一点?

4

1 回答 1

1

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"]
于 2012-12-31T04:10:20.163 回答