[英]Can't access class in nested ruby modules
I'm fighting with nested modules and access to classes in these modules in ruby. 我正在与嵌套模块进行斗争,并在ruby中访问这些模块中的类。
I created a simple example to show my problem. 我创建了一个简单的示例来展示我的问题。 app.rb and test.rb are placed in the same folder while sub_test.rb is placed in a sub-folder called test .
app.rb和test.rb放在同一文件夹中,而sub_test.rb放在一个名为test的子文件夹中。
app.rb app.rb
# /app.rb
require_relative 'test.rb'
Test::NotWorkingClass.work
test.rb test.rb
# /test.rb
module Test
require_relative 'test/sub_test'
class NotWorkingClass
def self.work
puts 'Test::NotWorkingClass.work'
end
end
end
test/sub_test.rb 测试/ sub_test.rb
# /test/sub_test.rb
module Test
module SubTest
Test::NotWorkingClass.work
end
end
When executing the app I'm getting this error: 在执行应用程序时,出现此错误:
/test/sub_test.rb:3:in `<module:SubTest>': uninitialized constant Test::NotWorkingClass (NameError)
When I commented out the execution of Test::NotWorkingClass in sub_test.rb everything works fine. 当我注释掉的Test :: NotWorkingClass的sub_test.rb一切执行工作正常。
And now the strange thing I didn't understand. 现在,我不明白的是奇怪的事情。 I modified my example by creating a file called not_working_class.rb in test folder and include it in the test.rb file:
我通过在测试文件夹中创建一个名为not_working_class.rb的文件并将其包含在test.rb文件中来修改了示例:
test.rb test.rb
# /test.rb
module Test
require_relative 'test/not_working_class'
require_relative 'test/sub_test'
end
test/not_working_class.rb 测试/ not_working_class.rb
# /test/not_working_class.rb
module Test
class NotWorkingClass
def self.work
puts 'Test::NotWorkingClass.work'
end
end
end
And now, the example works. 现在,该示例起作用了。
So why can't I access Classes defined in the test.rb file but can access them when defined in separate file? 那么,为什么不能访问在test.rb文件中定义的类,但是在单独的文件中定义时却可以访问它们呢?
As the error message suggests, test/sub_test.rb can not find Test::NotWorkingClass
. 如错误消息所示, test / sub_test.rb找不到
Test::NotWorkingClass
。
You should add require_relative "../test"
in test/sub_test.rb , and remove the require_relative 'test/sub_test'
in test.rb 您应该在test / sub_test.rb中添加
require_relative "../test"
,并在test.rb中删除require_relative 'test/sub_test'
So the problem is where the require statement is at. 因此,问题出在require语句所在的位置。
If you put require_relative "../test"
inside test/sub_test.rb it creates circular require because test.rb requires test/sub_test.rb 如果将
require_relative "../test"
放在test / sub_test.rb内,则会创建循环需求,因为test.rb需要test / sub_test.rb
If you put require_relative "../test"
inside test/sub_test.rb and then add require_relative "test/sub_test.rb"
inside app.rb then it'll work 如果您将
require_relative "../test"
放在test / sub_test.rb中,然后在app.rb中添加require_relative "test/sub_test.rb"
,那么它将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.