Search code examples
ruby-on-railsclass-variables

updating class variables in rails


I have a class variable named @@customers which I would like to continually update via a method.

I initialize the variable (as an empty array) at the top of my model. And then update it when the method update_customers is called:

class Customer
   @@customers = []

   def update_customers(new_customer)
      @@customers << new_customer
   end
end

I am concerned about @@customers being re-initialized to [] and losing the data. Could such re-initialization occur? When would it happen?


Solution

  • Nope; @@customers will not be re-initialized to [] when update_customers is called from a new Customer object. That is how class variables work.

    See http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/113-class-variables for an in-depth treatment of class variables.

    As mentioned there:

    There aren't very many cases that you would need to use class variables.`