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
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