0

好奇首选命名空间代码在使用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
4

1 回答 1

1

我认为 Zeitwerk 本身并不关心这一点。归根结底,controllers/api/users_controller.rb 仍然定义Api::UsersController并且 Zeitwerk 能够在任何一种情况下找到它。

作为基本规则,

module Api
  class UsersController
  end 
end

是首选样式,因此您可能应该坚持使用它。

https://github.com/fxn/zeitwerk/issues/57

于 2019-07-02T23:07:45.623 回答