我在RoR上做我的第一步,更习惯于Symfony。我想知道如何在RoR中复制特定的模式,类似于依赖注入。
在我的控制器中,我需要根据过滤器(在查询参数中传递)和current_user(作为记录的所有者)从数据库中获取记录。非常常见的用例!
我写了一个helper模块,然后在其中声明了一个类。我可以从控制器示例化这个类,但是我必须从控制器传递current_user和参数。我想问的是,这是否可以像我们在Symfony上使用依赖注入一样自动完成?
有一些代码可以解释:
# app/controllers/api_controller.rb
class ApiController < ApplicationController
def list
@list_helper = ListHelper.new(Product, params, current_user)
render :json => {
"items": @list_helper.items,
"page_count": @list_helper.page_count,
"current_page": @list_helper.current_page,
}
end
end
# app/helpers/application_helper.rb
module ApplicationHelper
def current_user
@current_user ||= User.find_by_id(session[:user_id]) if !!session[:user_id]
end
end
# app/helpers/list_helper.rb
module ListHelper
class ListHelper
attr_reader :page_count, :current_page
def initialize(active_record, params, current_user) # <-- there is a way to inject 2nd and 3rd?
@active_record = active_record
@current_user = current_user
@params = params
# ...doing some stuff
end
def items
# ...query
end
end
end
# and obviously in app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include ApplicationHelper
include ListHelper
end
尝试了“services”模式,但这很难传递active_record对象(用于helper类中的查询)。一个简单而好的方法是在对象初始化之前设置参数(也许是静态的?),由一个全球?,🤕或者通过在类中注入应用程序帮助程序🙀
提前感谢你,最好的问候
1条答案
按热度按时间72qzrwbm1#
您可以使用基于
ActiveSupport::CurrentAttributes
的Current.user
替换@current_user
。创建一个
app/models/current.rb
文件,如下所示:将
current_user
setter方法替换为:并使用全局可用的
Current.user
方法代替current_user
,而不需要将current_user
传递到其他模型中。