gpt4 book ai didi

ruby - rails 中的模型命名空间问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:33 26 4
gpt4 key购买 nike

我在 Rails 3.1 中遇到命名空间问题。我有一个类,我们称它为 a。

#/app/models/a.rb
class a
#some methods
def self.method_from_a
#does things
end
end

但我还有另一个在不同命名空间中具有相同名称的类。

#/app/models/b/a.rb
class b::a
def method
return a.method_from_a
end
end

当我调用 b::a.method 时,我得到:

NameError: uninitialized constant b::a::a

我确信这是一个简单的解决方案,我只是想念它。

最佳答案

前缀 a:::

class b::a
def method
return ::a.method_from_a
end
end

这(即作用域运算符)也有解释 here :

Constants defined within a class or module may be accessed unadorned anywhere within the class or module. Outside the class or module, they may be accessed using the scope operator, ::'' prefixed by an
expression that returns the appropriate class or module object.
Constants defined outside any class or module may be accessed
unadorned or by using the scope operator
::'' with no prefix.

顺便说一下,在 Ruby 中类名应该以大写字母开头。

关于ruby - rails 中的模型命名空间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969240/

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