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
def test
@@total += 1
render :text => @@total.to_s
end
end
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
on???
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?
Thanks!
firestoke
On 23 Apr 2008, at 16:12, firestoke wrote:
def test
@@total += 1
render :text => @@total.to_s
end
end
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
on???
Classes are reloaded between requests in development mode.
Fred
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.
-Danimal
On Apr 23, 2008, at 10:32 PM, FireStoke wrote:
Okay, I already tried it and the result is correct now. Thanks!
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.
Firestoke,
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?
-Danimal
Ok, I see it.
I will try to save my static data into db.
Thanks! :^)
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
development mode?
firestoke