Ruby on rails Rails使用单例类语法在类方法中自动加载具有相同名称的类
假设我在Rails应用程序的不同模块(全局名称空间/无名称空间和“Foo”)中有两个同名(“Bar”)的类。 这两个类分别位于“app/models/bar.rb”或“app/models/foo/bar.rb”中,因此由rails自动加载Ruby on rails Rails使用单例类语法在类方法中自动加载具有相同名称的类,ruby-on-rails,ruby,autoload,Ruby On Rails,Ruby,Autoload,假设我在Rails应用程序的不同模块(全局名称空间/无名称空间和“Foo”)中有两个同名(“Bar”)的类。 这两个类分别位于“app/models/bar.rb”或“app/models/foo/bar.rb”中,因此由rails自动加载 # "app/models/foo/bar.rb" module Foo class Bar def self.some_method end end end # "app/models/bar.rb" class Bar end
# "app/models/foo/bar.rb"
module Foo
class Bar
def self.some_method
end
end
end
# "app/models/bar.rb"
class Bar
end
我在Foo命名空间中有另一个类,它在类方法中使用Bar类
module Foo
class Qux
class << self
def something
Bar.some_method # This raises a NoMethod error because
# it uses the Bar defined in the global namespace
# and not the one in Foo
end
end
end
end
这会导致Rails从“app/models/Bar.rb”而不是“app/models/foo/Bar.rb”加载Bar
。
如果我用def self.something
定义Qux.something
,那么.name
是“Foo::Qux”,而不是nil,并且自动加载工作正常
我认为目前有3种解决此问题的方法:
1) 重命名其中一个栏
类2) 在任何地方使用
self.
语法3) 命名空间
Bar
和Foo::Bar
显式无处不在
我不喜欢这些选项中的任何一个,因为:
1) Bar
正是最合适的名称2)
课你看到这个了吗:我想它涵盖了你的一些主题
klass_name = name.presence || "Object" # from active_support/dependencies.rb