Rails 6 convention for declaring namespaced classes? zeitwerk autoloader

爱⌒轻易说出口 提交于 2021-01-29 05:21:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!