Reputation: 3225
I just want to have an array as global, so when I add or remove an element, it can be reflected anywhere in the class.
For example:
class something
@@my_array = Array.new
def self.action_1
@@my_array << 1
@@my_array << 2
@@my_array << 3
end
def self.how_many_elements
puts "# of elements: " + @@my_array.size.to_s
end
end
If i do the following:
something.action_1 => from controller_a
something.how_many_elements => from controller b
I always get the following output:
"# of elements: 0"
Why?
Upvotes: 1
Views: 2139
Reputation: 211740
It's a common mistake to think that you can stash things in your classes and they will persist between requests. If this happens it is purely coincidence and it is a behavior you cannot depend on.
Using global variables in this fashion is almost a bad idea. A properly structured Rails application should persist data in the session
, the database, or the Rails.cache
subsystem.
Each request serviced by Rails in development mode will start with a virtually clean slate, where all models, controllers, views and routes are reloaded from scratch each time. If you put things in a class thinking it will be there for you the next time around, you're going to be in for a surprise.
For saving things that are not important, use the Rails cache or the session facility. For saving things that are important, use a database.
Upvotes: 5
Reputation: 96997
Use class variables:
class something
@@my_array = []
def self.action_1
@@my_array << 1
@@my_array << 2
@@my_array << 3
end
def self.how_many_elements
puts "# of elements: " + @@my_array.size
end
end
Upvotes: 1