我正在使用Rails Warden插件。它定義了返回當前用戶的'用戶'helper method。請參閱源代碼的鏈接。如何在Rails3中訪問Warden當前用戶的業務邏輯
現在我有一個業務邏輯對象沒有任何控制器的引用。但我想獲得當前用戶。有沒有什麼方法可以訪問它?
我已經試過
ActionController::Base.helpers.user
甚至
RailsWarden::Mixins::HelperMethods.user
沒有運氣。謝謝。
我正在使用Rails Warden插件。它定義了返回當前用戶的'用戶'helper method。請參閱源代碼的鏈接。如何在Rails3中訪問Warden當前用戶的業務邏輯
現在我有一個業務邏輯對象沒有任何控制器的引用。但我想獲得當前用戶。有沒有什麼方法可以訪問它?
我已經試過
ActionController::Base.helpers.user
甚至
RailsWarden::Mixins::HelperMethods.user
沒有運氣。謝謝。
現在我有一個業務邏輯對象 ,沒有任何引用 控制器。但我想 得到當前用戶。有什麼辦法可以訪問這個嗎?
那麼,爲什麼你不能只將當前用戶傳遞給這些方法呢?
另外,你可以將它們混合。
我極力勸阻你寫的靜態助手(它不是Java,它是紅寶石!)。 相反,你需要的幫手把它們作爲一個模塊:
module SuperLogic
def calculate_stuff(current_user=nil)
(current_user || user || self).bills.sum
end
edn
然後包括這在你需要它:
# user model
class User
include SuperLogic
#it will get the `calculate_stuff` method
end
# controller
include SuperLogic
# so you can use it as one of
calculate_stuff user
calculate_stuff
等等...
另外,你的訪問您的業務邏輯,您可以創建類的實例而不是「靜態」方法(在紅寶石中,它們是「類」方法):
# controller
def calculate
@result = BusinessLogic.new(user).calculate_stuff
end
這可能是最容易做的事情。
真的,你不需要訪問業務對象中的整個HTTP上下文(我甚至沒有談及測試它)。
謝謝。我用過這個:http://github.com/bokmann/sentient_user http://github.com/astrails/let_my_controller_go http:// rails-bestpractices。COM /職位/ 47取入當前用戶爲中的模型 – lzap 2011-04-01 09:32:38
我想到業務邏輯的方式,它位於控制器和模型之間。我認爲將請求的實例傳遞給邏輯方法是可以的,並且由於您使用了warden,所以您可以從'request.env''warden']。user'獲得用戶。
我還沒有遇到一個好的理由,不要讓邏輯方法成爲模塊的靜態(self。)方法。也許Dmytrii的建議適用於你,但我更願意'要求'而不是動態地包含一次性邏輯位。
您正試圖從模型獲得acces? – fl00r 2011-03-29 13:00:09
不,來自只有靜態方法的對象。這些是從控制器調用的。 – lzap 2011-03-30 08:21:03
您是否嘗試過'包括Rack :: Test :: Methods'? https://github.com/hassox/rails_warden/wiki/Troubleshootings – 2011-04-01 04:20:27