Hi there, I am new in Ruby.
I got a question, maybe it's stupid.
There is controller named 'home', and a action named 'test' existed.
And I defined a class variable named '@@total'
looks like this:
class HomeController < ApplicationController
@@total = 0
@@total += 1
render :text => @@total.to_s
The logic is very clear and simple, I wanna increase the value of
@@total when I call it every time.
So I connect the url: http://localhost:3000/home/test to try it.
But it ALWAYS responses me "1", there is no accumulation. What's going
I read the Ruby book and api document, they say the class variable
should act likes a static variable in Java or C++.
But I don't get the result I espected. Could somebody tell me why?
Classes are reloaded between requests in development mode.
Yup, what Fred said.
Switch to production mode and try it then.
Or, perhaps use the session to store the accumulator. That would be
per-user session, though.
If you want to persistent, across-the-application accumulator, use a
file or the DB.
Okay, I already tried it and the result is correct now. Thanks!
One more question, can I turn off the class auto-reload mechanism in
You shouldn't depend on it. For instance, if you ever do any sort of load balancing your application will break.
If you need a value to persist, either put it in the session or in the database.
I'm sure you could, but the question is: why? part of the whole power
of development mode is the class reloading. That way, as you edit your
code, you don't have to constantly restart your server. If you want to
fiddle without the reloading, why not just stay in production mode?
Ok, I see it.
I will try to save my static data into db.