[英]How to properly set up, make or include concern in Rails
通常,關注點位於
app/controllers/concerns
。
但我想為管理方面制定和分離關注點。
app/controllers/admin/concerns
鑒於我設置了一些示例代碼,
# app/controllers/admin/concerns/test.rb
module Test
extend ActiveSupport::Concern
included do
before_action :test
end
def test
render json: 'test concern'
end
end
# 也試過了...,
module Admin
module Test
extend ActiveSupport::Concern
included do
before_action :test
end
def test
render json: 'test concern'
end
end
end
# 然后包含喜歡,包含 Admin::Test
如何在我的管理控制器中正確調用或包含測試問題。
class Admin::ShopsController < Admin::BaseController
include Admin::Test # doing this,
# got uninitialized constant Admin::Test
end
相關解釋已經寫在官方指南中。
好吧,Rails 有一個類似於 $LOAD_PATH 的目錄集合,可以在其中查找 post.rb。 該集合稱為 autoload_paths,默認情況下它包含:
應用程序和引擎中任何名為 app/*/concerns 的現有二級目錄。
https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
未加載app/controllers/admin/concerns
的原因是它不是二級目錄。
由於第二級關注目錄中的文件會自動加載,在這種情況下,您應該將 test.rb 文件放在app/controllers/concerns/admin
。
或者將app/controllers/admin/concerns
到自動加載路徑,但不強烈推薦這樣做,因為這不符合 Rails 設計模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.