【问题标题】:Rails 6 convention for declaring namespaced classes? zeitwerk autoloaderRails 6 声明命名空间类的约定? zeitwerk 自动加载器
【发布时间】:2019-06-19 21:06:26
【问题描述】:

很好奇在使用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 会在 2nd 样式中引发 Style/ClassAndModuleChildren 错误,并且存在轻微的行为差异:

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

【问题讨论】:

标签: ruby-on-rails-6


【解决方案1】:

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

一般来说,

module Api
  class UsersController
  end 
end

是首选风格,所以你应该坚持下去。

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

【讨论】:

  • ...您是打开该问题的人。我很笨。
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2011-09-09
相关资源
最近更新 更多