Search code examples
ruby-on-railsnginxamazon-ec2webrickclass-variables

@@classVariable in ruby on rails turns uninitialized on nginx - ec2


I have a class variable that I initialize, that later magically becomes uninitialized by itself... When developing locally on rails' default server (WEBrick), there is no problem. This only happens on nginx on ec2. Here's some code..

def TestController < ApplicationController
  @@classVariable = ""

  def index
    @@classVariable = "What's up homie"
    log(@@classVariable)
  end

  def callThisMethodViaAJAXFromJavascript
    log("reached this method")
    log(@@classVariable)
  end

  def log(str)
    File.write("aValidPath", str)
  end

end

Here's what I do: When I load the page on test/index, the index method executes, and properly logs @@classVariable as:
"What's up homie"

But when I call the method callThisMethodViaAJAXFromJavascript via AJAX from the frontend, my log file looks like:
"reached this method"
""

Again, this ONLY occurs on nginx on, ec2 (OS is ubuntu). When I run locally on WEBrick, this NEVER happens.

Any ideas? Thank you very much.


Solution

  • You don't say how you're using nginx (as a reverse proxy to some unicorn instances, with passenger etc) but either way you would typically have multiple instances of your application. Each one is a separate process so setting a class variable in one process has no effect on the other process.

    Nginx will balance requests between the rails instances - so the index page is served by one instance and the ajax action will frequently be served by another process where the clas variable is still the empty string.

    In development with webrick there is only one rails instance so you don't encounter this problem. I'm not sure what you were trying to do but class variables are not a good way to preserve state across requests