背景:
这是问题所在,简化为最小的例子:
# bar.rb
class Bar
end
# foo/bar.rb
module Foo::Bar
end
# foo.rb
class Foo
include Foo::Bar
end
# runner.rb
require 'bar'
require 'foo'
Run Code Online (Sandbox Code Playgroud)
? ruby runner.rb
./foo.rb:2: warning: toplevel constant Bar referenced by Foo::Bar
./foo.rb:2:in `include': wrong argument type Class (expected Module) (TypeError)
from ./foo.rb:2
from runner.rb:2:in `require'
from runner.rb:2
在我的应用程序中,我有
VeryUniqueModule::Foo
# and…
VeryUniqueModule::Bar
Run Code Online (Sandbox Code Playgroud)
Foo并且Bar每个都是为不同的服务.我的应用程序的一部分必须动态地确定要引用的模块,它可以这样做:
def service_api
# @relevant_object.service is a string that is either 'Foo' or 'Bar'
VeryUniqueModule.const_get(@relevant_object.service)
end
Run Code Online (Sandbox Code Playgroud)
稍后会详细介绍.
我刚刚更新了一个库,现在它有自己的顶级Foo类(这是一个糟糕的设计).现在,当我尝试调用时@relevant_object.service_api::A_CONSTANT,我的应用程序抱怨图书馆 Foo没有A_CONSTANT.
回到service_api上面 - 我以为那const_get是回归班级本身.事实上,我知道它是.如果我在irb所有内容中按照预期启动它- 返回值是类本身,我可以调用类中的东西.所以…
A_CONSTANT的Class对象service_api,而不是我正在使用的字符串eval或类似的那些时髦的东西 - 应该没有任何命名空间问题,我直接指的是一个对象!service_api该如何修复以便它将返回,嗯,"完整路径"?