问题
Curious what the preferred namespaced code should look like in rails 6 which uses zeitwerk for autoloading.
Previously I used:
# app/controllers/api/users_controller.rb
module Api
class UsersController
def index
render json: {}
end
end
end
With zeitwerk should we now use: ???
# app/controllers/api/users_controller.rb
class Api::UsersController
def index
render json: {}
end
end
Based on example in https://weblog.rubyonrails.org/2019/2/22/zeitwerk-integration-in-rails-6-beta-2/ it appears the 2nd style is being used.
By default rubocop will raise Style/ClassAndModuleChildren
error with 2nd style and there are slight behavior differences:
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
回答1:
I don't think Zeitwerk itself cares about that either way. At the end of the day, controllers/api/users_controller.rb still defines Api::UsersController
and Zeitwerk is able to find it in either case.
As a general rule,
module Api
class UsersController
end
end
is the preferred style, so you should probably stick with that.
See https://github.com/fxn/zeitwerk/issues/57
来源:https://stackoverflow.com/questions/56675838/rails-6-convention-for-declaring-namespaced-classes-zeitwerk-autoloader