Seguridad de subprocesos de una variable de clase en Rails: ¿funcionará?

Estoy usando el Ruby Money gem in a multi-tenant (SaaS) Rails app, and am looking for a good way to make the Money.default_currency be set to an Account's preference for each request. I have several currency-related models in the app that use the Money class.

I have everything working properly in development, but I'm just looking for some feedback on whether or not the solution with have repercussions in production.

Here's what I did in my ApplicationController (irrelevant code removed for brevity):

class ApplicationController < ActionController::Base
  before_filter :set_currency


  def set_currency
    Money.default_currency = && current_account.currency.present? ?
                                                 current_account.currency : 'USD')

So the code above will set the default_currency class variable to the current account's preference, or default back to 'USD' if there isn't one.

By the way, here's the relevant default_currency code in the Money class:

class Money

  # Class Methods
  class << self

    # The default currency, which is used when is called without an
    # explicit currency argument. The default value is"USD"). The
    # value must be a valid +Money::Currency+ instance.
    # @return [Money::Currency]
    attr_accessor :default_currency


So, will this work as expected in a multi-user setting? Anything else I need to do?

preguntado el 31 de enero de 12 a las 16:01

1 Respuestas

Most rails apps don't run in multithreaded mode - a given instance is only ever handling one request at a time (this is the default).

If your app was in multithreaded mode this would be dangerous - Money.default_currency could get changed halfway through a request by the new request that has just come in. If you did want to make this thread safe, you could use the Thread.current hash to have per thread values of default_currency

Respondido el 31 de enero de 12 a las 20:01

Thanks, I'm not running Rails in multi-threaded mode so that's what I figured. Just wanted to get another opinion, so thank you! - Summerville

@summerville It has been a while since this question, but wanted to point out that as things move forward, there are increasingly cases where servers (e.g. unicorn, and even passenger) can be configured in a way that would allow certain multi-threaded operations to occur. So you're probably safe ... for now, but I would suggest you either avoid cases like yours, and follow Frederick's advice to use Thread.current. You're dealing with money here, so ... it matters if you get it wrong :-) - Tom Harrison

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.