用于声明命名空间类的 Rails 6 约定?zeitwerk 自动加载器 [英] Rails 6 convention for declaring namespaced classes? zeitwerk autoloader

查看:50
本文介绍了用于声明命名空间类的 Rails 6 约定?zeitwerk 自动加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道在使用 zeitwerk 进行自动加载的 Rails 6 中首选命名空间代码应该是什么样子.

Curious what the preferred namespaced code should look like in rails 6 which uses zeitwerk for autoloading.

以前我用过:

# app/controllers/api/users_controller.rb
module Api
  class UsersController
    def index
      render json: {}
    end
  end 
end

对于 zeitwerk,我们现在应该使用:???

With zeitwerk should we now use: ???

# 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/ 看来正在使用第二种样式.

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.

默认情况下,rubocop 会在第二个样式中引发 Style/ClassAndModuleChildren 错误,并且存在轻微的行为差异:

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

推荐答案

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

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.

作为一般规则,

module Api
  class UsersController
  end 
end

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

is the preferred style, so you should probably stick with that.

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

这篇关于用于声明命名空间类的 Rails 6 约定?zeitwerk 自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆