gpt4 book ai didi

ruby - Ruby 脚本中未初始化的常量错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:46 24 4
gpt4 key购买 nike

我正在为一个 Web 应用程序建模,您可以通过单击某个链接进入另一个应用程序页面。我决定做这样的事情:

文件 C:/Sandbox/common_page.rb:

require_relative "./pageA"
require_relative "./pageB"
require_relative "./pageC"
require_relative "./pageD"
class CommonPage
def pageA
# click_pageA_link
pageA.new
end
def pageB
# click_pageB_link
pageB.new
end
def pageC
# click_pageC_link
pageC.new
end
def pageD
# click_pageD_link
pageD.new
end
# and so on for other pages..
end

文件 C:/Sandbox/pageA.rb:

require_relative "./common_page"
class PageA < CommonPage
def pageA
self
end
end

文件 C:/Sandbox/pageB.rb:

require_relative "./common_page"
class PageB < CommonPage
def pageB
self
end
end

类似的代码将用于表示其他页面的类。如果我使用此代码运行文件 C:/Sandbox/test.rb:

require_relative "./pageA"
pA = PageA.new

我收到这个错误:

C:/Sandbox/pageB.rb:2:in `<top (required)>': uninitialized constant CommonPage (NameError)
from C:/Sandbox/common_page.rb:2:in `require_relative'
from C:/Sandbox/common_page.rb:2:in `<top (required)>'
from C:/Sandbox/pageA.rb:1:in `require_relative'
from C:/Sandbox/pageA.rb:1:in `<top (required)>'
from C:/Sandbox/test.rb:1:in `require_relative'
from C:/Sandbox/test.rb:1:in `<main>'

当我尝试创建其他类的实例时,也会弹出类似的错误。有人可以解释这里发生了什么以及如何避免这个问题吗?

最佳答案

显然不能满足循环依赖。如果鸡蛋需要母鸡,而母鸡从鸡蛋中孵化出来,那么如果你还没有,那么你就没有。为什么 common_page.rb 必须要求 pageA?从 common_page.rb 中删除 require,创建一个单独的 my_project.rb,创建一个 my_project 目录,移动其中的所有其他文件,并 require它们来自 my_project.rb,如下所示:

require_relative 'my_project/common_page'
require_relative 'my_project/pageA'
require_relative 'my_project/pageB'
require_relative 'my_project/pageC'
require_relative 'my_project/pageD'

关于ruby - Ruby 脚本中未初始化的常量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16253013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com