[英]How to properly set up, make or include concern in Rails
Usually, concerns are located in通常,关注点位于
app/controllers/concerns
. app/controllers/concerns
。
But I want to make and separate concerns for admin side.但我想为管理方面制定和分离关注点。
app/controllers/admin/concerns
Given I set up some sample codes,鉴于我设置了一些示例代码,
# 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
# ALSO tried..., # 也试过了...,
module Admin
module Test
extend ActiveSupport::Concern
included do
before_action :test
end
def test
render json: 'test concern'
end
end
end
# then include like, include Admin::Test # 然后包含喜欢,包含 Admin::Test
How to properly call or include the test concern in my admin controller.如何在我的管理控制器中正确调用或包含测试问题。
class Admin::ShopsController < Admin::BaseController
include Admin::Test # doing this,
# got uninitialized constant Admin::Test
end
Related explanation has been written in official guide.相关解释已经写在官方指南中。
All right, Rails has a collection of directories similar to $LOAD_PATH in which to look up post.rb.好吧,Rails 有一个类似于 $LOAD_PATH 的目录集合,可以在其中查找 post.rb。 That collection is called autoload_paths and by default it contains:该集合称为 autoload_paths,默认情况下它包含:
Any existing second level directories called app/*/concerns in the application and engines.应用程序和引擎中任何名为 app/*/concerns 的现有二级目录。
https://guides.rubyonrails.org/autoloading_and_reloading_constants.html https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
The reason why app/controllers/admin/concerns
isn't loaded is it's not a second level directory.未加载app/controllers/admin/concerns
的原因是它不是二级目录。
Since files in the second level concerns directory are automatically loaded, in this case you sould put the test.rb file in the app/controllers/concerns/admin
.由于第二级关注目录中的文件会自动加载,在这种情况下,您应该将 test.rb 文件放在app/controllers/concerns/admin
。
Or adding app/controllers/admin/concerns
to autoload path, but it's not highly recommended because this is out of rails design pattern.或者将app/controllers/admin/concerns
到自动加载路径,但不强烈推荐这样做,因为这不符合 Rails 设计模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.