Class variables and modules

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

On Fri, Jun 4, 2010 at 7:26 PM, Ill E. [email protected] wrote:
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 :wink:

Robert D. wrote:

On Fri, Jun 4, 2010 at 7:26 PM, Ill E. [email protected] wrote:
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 :wink:

Much thanks from illeverbe

As a side note:

On 2010-06-04 10:26:50 -0700, Ill E. said:

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

Array#push modifies the receiver, so you can simply say:

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

or even:

@@history << @@incoming_state.flatten