Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么以这种方式构造代码会导致顶级常量警告?我如何修复它?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 为什么以这种方式构造代码会导致顶级常量警告?我如何修复它?

Ruby on rails 为什么以这种方式构造代码会导致顶级常量警告?我如何修复它?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我的应用程序代码的结构如Rails 3.2所示。如果我进入Rails控制台并输入Foo::Bar::FooBar它将返回以下警告: warning: toplevel constant FooBar referenced by Foo::Bar::FooBar 应用程序代码及其所在的文件: # app/models/foo/bar/foo_bar.rb module Foo class Bar class FooBar end end end # app/models

我的应用程序代码的结构如Rails 3.2所示。如果我进入Rails控制台并输入
Foo::Bar::FooBar
它将返回以下警告:

warning: toplevel constant FooBar referenced by Foo::Bar::FooBar
应用程序代码及其所在的文件:

# app/models/foo/bar/foo_bar.rb
module Foo
  class Bar
    class FooBar
    end
  end
end

# app/models/foo/bar.rb
module Foo
  class Bar
  end
end

# app/models/foo_bar.rb
class FooBar
end
我的自动加载路径没有从Rails默认值更改

我能够解决这个问题的一种方法是将以下代码添加到
Foo::Bar::FooBar
。然而,它感觉很脏,我想知道是否有一个配置选项或其他一些我做错的事情可以解决这个问题

# app/models/foo/bar/foo_bar.rb
module Foo
  # This line of code removes the warning and makes class methods execute
  # on the Foo::Bar::FooBar class instead of the FooBar class.
  class Bar; end

  class Bar
    class FooBar
    end
  end
end

基本问题是,在重叠的范围内,对不同的类重用相同的名称。您可能可以做一些聪明的事情,让Ruby以您想要的方式解析常量名称,但这种“解决方案”从根本上说是脆弱的。(如果一个新版本的Ruby对常量的查找方式做了微小的改变,或者您转移到另一个Ruby实现,该怎么办?)


为什么不在模块中命名顶级
FooBar
model类呢?(您必须将文件移动到与模块同名的子目录中。)

应该注意的是,在同一应用程序中,我还有其他加载Foo::Baz和Baz的情况,它们从来没有任何问题。另外,如果我用纯Ruby实现这个,就不会有问题。只有当我在Rails应用程序中执行此操作时,它才会成为一个加载问题。