我很好奇在使用zeitwerk进行自动加载的Rails6中,首选的命名空间代码应该是什么样子。
之前我使用的是:
# app/controllers/api/users_controller.rb
module Api
class UsersController
def index
render json: {}
end
end
end对于zeitwerk,我们现在应该使用:?
# app/controllers/api/users_controller.rb
class Api::UsersController
def index
render json: {}
end
end根据https://weblog.rubyonrails.org/2019/2/22/zeitwerk-integration-in-rails-6-beta-2/中的示例,似乎正在使用第二种风格。
默认情况下,rubocop将在第二个样式中引发Style/ClassAndModuleChildren错误,并且有一些细微的行为差异:
module Foo
class Bar
def fud
end
end
end
module Foo
class Woo
def woo_woo
Bar.new.fud
end
end
endclass Foo::Bar
def fud
end
end
class Foo::Woo
def woo_woo
# NameError: uninitialized constant Foo::Woo::Bar
Bar.new.fud
# no error
Foo::Bar.new.fud
end
end发布于 2019-07-03 07:07:46
我认为Zeitwerk本身并不关心这两种方式。归根结底,控制器/api/usersControler.rb仍然定义了Api::UsersController,并且Zeitwerk能够在任何一种情况下找到它。
作为一般规则,
module Api
class UsersController
end
end是首选的样式,所以您可能应该坚持使用它。
https://stackoverflow.com/questions/56675838
复制相似问题