For example, the following code:
class FoosController < ApplicationController
def index
if [email protected]?
render :locals => {:bar => @foo}
return
else
@foo = rand 10
render :locals => {:bar => @foo}
end
end
end
if I load localhost:3000/foos
multiple times, it will show different values, and it is no surprise if it is development mode, because Rails reload the controller (and model and view) every time a browser request comes in.
But even when in production mode, when everything is loaded and stay there, @foo
's value won't stay across browser requests? Every time reloading the page on the web browser, a different number is shown. So Rails will wipe all values clean each time? Is there a way to cache or "memoize" the results across requests if we don't use a DBMS?
Surprisingly, I just tried using a class variable, and in development mode, it gives a different number each time. In production mode, the number stays the same on Firefox, and then Chrome will also show that number all the time, until the server is restarted:
class FoosController < ApplicationController
@@foo = nil
def index
if !@@foo.nil?
render :locals => {:bar => @@foo}
return
else
@@foo = rand 10
render :locals => {:bar => @@foo}
end
end
end
Why can a class variable memoize but an instance variable can't? Is using a class variable a reliable way to "remember things" across request reliably in Rails 2.x, 3.x and Ruby 1.8.7 and 1.9.2?