我正在使用Sorcery
gem。
我有sessions_controller
处理登录/注销。我想提取与控制器无关的代码,如表单验证和将用户签名到表单对象。
但是,要登录用户,我需要访问sessions_controller,因为它需要访问控制器上下文。显然,我可以将控制器传递给表单对象,但我根本不喜欢将它们绑定。这是它的外观:
# SessionsController:
# ...
def create
@form = SignInForm.new(session_params)
@form.set_controller self
if @form.valid?
redirect_signed_in_users
else
render :new, status: :unauthorized
end
end
# SignInForm
( unnecessary stuff omitted
class SignInForm
include ActiveModel::Model
include Virtus.model
attribute :email, String
attribute :password, String
attribute :controller, ActionController::Base, writer: :private
validates_presence_of :email, :password
validate :valid_credentials
def set_controller(controller)
self.controller = controller
end
private
def valid_credentials
errors.add(:base) unless controller.login(self.email, self.password, self.remember_me)
end
end
有什么想法吗?