Class Variable

Hi everyone,

I have a question about class variable in Rails:

I have a class Point that contains an class variable
@@color_points="green"

In a first web Page I want to set up this variable, hence i do
Point.color_points = "green" then i test it using puts
Point.color_points ( = green, it works,yes!)
Then i have a link_to instruction that points to another web page.
On this one (the other one), I just want to print Point.color_points,
but now its value is "".

DOes anyone know why and could explain me?

Each request is isolated. At the end of the first request, all the
variables you've set disappear into the ether. If you want something
to persist, you need to store it - in the DB, the session, or
somewhere else.
The second request builds up new instances of all the objects - so the
class variable is back to its default value.

thelo.g thelo wrote in post #1018888:

Hi everyone,

I have a question about class variable in Rails:

I have a class Point that contains an class variable
@@color_points="green"

In a first web Page I want to set up this variable, hence i do
Point.color_points = "green" then i test it using puts
Point.color_points ( = green, it works,yes!)
Then i have a link_to instruction that points to another web page.
On this one (the other one), I just want to print Point.color_points,
but now its value is "".

DOes anyone know why and could explain me?

In addition, you shouldn't be using class variables. You can forget
they exist.

class Dog
  @count = 0

  def initialize
    Dog.count += 1
  end

  def self.count
    @count
  end

  def self.count=(val)
    @count = val
  end

end

d1 = Dog.new
puts Dog.count

d2 = Dog.new
puts Dog.count

--output:--
1
2

Bwah! Hahahah!

What tosh...

class Dog
@count = 0

def initialize
Dog.count += 1
end

def self.count
@count
end

def self.count=(val)
@count = val
end

end

If you want to be entirely nit-picky those are class instance
variables rather than class variables.

Fred

Michael Pavling wrote in post #1018902: