class variables and modules

I

Ill Everbe

I am trying to keep a history of object state in a parent class using a
class variable. This works per example 1 using child method
update_state. but if i mixin a module to update_state (so as not to
repeat update_state every), per example 2 i get different behavior. i do
not understand why.
########################### example 1 ########################
class A
def initialize
@@history= []
@@incoming_state = ['initial incoming state']
end

def update_history
@@history = @@history.push( @@incoming_state.flatten)
end

def history
@@history
end
end

class B < A
def new_state
@another_state = ["new state"]
end
attr :another_state
def update_state
@@incoming_state = self.another_state
end
end
a = A.new
b=B.new
b.new_state
b.update_state
b.update_history
b.update_state
b.update_history
p b.history
################################ example 2
################################

class A
def initialize
@@history= []
@@incoming_state = ['initial incoming state']
end

def update_history
@@history = @@history.push( @@incoming_state.flatten)
end

def history
@@history
end
end

module Keeper
def update_state
@@incoming_state = self.another_state
end
end

class B < A
include Keeper
def new_state
@another_state = ["new state"]
end
attr :another_state
end

a = A.new
b=B.new
b.new_state
b.update_state
b.update_history
b.update_state
b.update_history
p b.history
 
R

Robert Dober

Short answer: Do not use class variables, period! Because they are
shared amongst subclasses.
Long answer: Ok that's exactly what you want.... include Keeper into A
and leave the subclasses alone ;)
 
I

Ill Everbe

Robert said:
Short answer: Do not use class variables, period! Because they are
shared amongst subclasses.
Long answer: Ok that's exactly what you want.... include Keeper into A
and leave the subclasses alone ;)

Much thanks from illeverbe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top