好奇首选命名空间代码在使用zeitwerk进行自动加载的 rails 6 中应该是什么样子。
以前我用过:
# 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
使用 2nd 样式引发错误,并且存在轻微的行为差异:
module Foo
class Bar
def fud
end
end
end
module Foo
class Woo
def woo_woo
Bar.new.fud
end
end
end
class 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