Reputation: 31
I was trying to get a dynamic array for in RUBY which will be changed dynamically. I could not able to push to class variable. Can any one help how can i do that please see the below code.
class SampleController < ApplicationController
@@array = []
@@x = 0
def ajax_data
y = (rand()*100).round()
@@array << [@@x,y]
@@x += 1
end
end
My Question is that the class variable @@array
should increase the size of the array whenever we call to the method ajax_data
but it always gives the output of one value like this [ [0, y] ]
. I want to increase the @@array and @@x
values .
How can we do that ?
Upvotes: 0
Views: 242
Reputation: 3222
Ruby on Rails, in development mode, by default reloads your source files on each request. Since you're saving your "program"'s state in class variables, the changes get wiped out by the reloading of your classes.
By the way, class variables are normally used with much caution, as they are essentially global. Especially in a Rails web application. Save any state in a database, not in your classes' context.
Update:
Remember that web server processes are usually supposed to be stateless. Also, you usually have multiple processes running in production, which means that your counter would be different between requests depending on which process would answer a request. Also, processes can be restarted, meaning you counter would be lost.
In Rails, if something is this tricky, it usually means you're trying to do something that you shouldn't do :)
If you really don't want to use a DB, and if the counter is not supposed to be global for all visitors of your page, you could try storing the counter in a cookie: http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html
Upvotes: 3