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?

On 28 August 2011 12:16, thelo.g thelo [email protected] wrote:

In a first web Page I want to set up this variable
then i test it using puts, it works,yes!
Then i have a link_to instruction that points to another web page.
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. You should use class instance variables instead:

class Dog
@count
end

However, the web is a stateless world, and nothing survives between
requests. Therefore, if you want data to persist, you have have to
store it in a cookie, sessions, a file, or a db.

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

On 28 August 2011 14:55, 7stud – [email protected] wrote:

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

Bwah! Hahahah!

What tosh…

On Aug 28, 3:14pm, 7stud – [email protected] wrote:

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 P. wrote in post #1018902:

On 28 August 2011 14:55, 7stud – [email protected] wrote:

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

Bwah! Hahahah!

What tosh…

Live and learn.