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

标签 ruby namespaces ruby-1.9

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

相关文章:

ruby-on-rails - Ruby 1.9、Rails 2.3.9 以及数据库和 erb View 中的 unicode 字符,仍然不行吗?

ruby-on-rails - Rails 中 JavaScript 资源的编码错误

ruby - RSpec 中的 'valid?' 是什么?我在哪里可以看到它?

ruby-on-rails - 在 Rails 的 LESS 文件中使用数据库值

xml - 如何使用 xslt 向元素添加变量命名空间

c# - 如何解决 BlazorServer 默认项目解决方案中的命名空间错误(VisualStudio 代码)

ruby-on-rails - 在跟踪变量 n 的方法中创建循环

ruby - 如何使用 Nokogiri 获取元关键字?

python - 安装的包窃取命名空间

ruby - 为什么 YAML.load 返回错误的数值?