简体   繁体   中英

How to handle global variables in Ruby on Rails

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM