我在多租戶(SaaS)Rails應用程序中使用Ruby Money gem,並且正在尋找一種讓Money.default_currency
設置爲每個請求的帳戶首選項的好方法。我在使用Money類的應用程序中有幾個與貨幣相關的模型。Rails中類變量的線程安全性 - 這是否可行?
我已經在開發過程中正常工作,但我只是在尋找一些有關是否在生產中引起反響的解決方案的反饋。
這是我在我的ApplicationController沒有(爲簡潔,刪除不相關的代碼):
class ApplicationController < ActionController::Base
before_filter :set_currency
private
def set_currency
Money.default_currency = Money::Currency.new(current_account.present? && current_account.currency.present? ?
current_account.currency : 'USD')
end
end
所以上面的代碼將設置default_currency
類變量經常賬戶的偏好,或默認回到如果「美元」沒有一個。
順便說一句,這裏的相關default_currency
代碼Money類:
class Money
# Class Methods
class << self
# The default currency, which is used when +Money.new+ is called without an
# explicit currency argument. The default value is Currency.new("USD"). The
# value must be a valid +Money::Currency+ instance.
#
# @return [Money::Currency]
attr_accessor :default_currency
end
end
因此,將這項工作作爲有望在多用戶環境?還有什麼我需要做的?
謝謝,我沒有在多線程模式下運行Rails,所以這就是我的想法。只是想獲得另一個意見,所以謝謝! – summerville 2012-01-31 23:24:58
@summerville自從這個問題已經有一段時間了,但是要指出,隨着事情的發展,越來越多的情況下服務器(例如獨角獸,甚至乘客)可以配置成允許某些多線程操作發生。所以你現在可能是安全的,但我建議你要麼避免類似你的情況,而要遵循Frederick的建議來使用Thread.current。你在這裏處理金錢,所以...如果你弄錯了,它很重要:-) – 2012-11-16 18:01:54