我在 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/