Source Code : 
require 'logger'
$log Logger.new(STDOUT)
$log.level Logger::INFO
$log
.progname "LifecycleDemo"
$log.formatter proc { |severitydatetimeprognamemsg|
    
#"#{datetime.strftime("%Y-%b-%d %a %H:%M")} #{severity} #{progname} {#{msg}}\n"
    
"#{msg}\n"
  
}
#$log.datetime_format = "%a %Y-%m-%d %H:%M"
 
 
class FirstClass
  
@@grandClass "FirstClassVar" # class level variable to track
  
def initialize
    
@grandVar "FirstInstanceVar" # instance variable to track
    
$log.info("! FirstClass init, #{ids}")
  
end
  def grand
    $log
.info("> FirstClass grand, #{ids}")
  
end
 
  def ids
      
"#{self.class.name}:: #{@@grandClass}:#{@@grandClass.object_id}, [email protected]}:[email protected]_id}"
  
end
end
 
class SecondClass FirstClass
  def initialize
    
@ego_hilite "-" 15
    super
    $log
.info("! Second class init, #{ids}")
  
end
  def spill_it
    $log
.info("> Spill It call, #{ids}")
  
end
  def alter_ego
      
@grandVar "SecondInstanceVar"
      
@@grandClass "SecondClassVar"
      
$log.info("\[email protected]_hilite} Ego altered by the #{self.class.name} [email protected]_hilite}\n\n")
  
end
end
 
class ThirdClass SecondClass
  
@@grandClass "ThirdClassStatic"
  
def initialize
    super
    $log
.info("! 3rd class init, #{ids}")
  
end
  def alter_ego
      
@grandVar "ThirdInstanceVar"
      
@@grandClass "ThirdClassVar"

[Login or Register to remove this advertisement]

      
$log.info("\[email protected]_hilite} Ego altered by the Third Class [email protected]_hilite}\n")
  
end
end
 
def test
(instance)
    
hilite "*" 20
    $log
.info("\n\n#{hilite} Testing instance of #{instance.class.name} BEGIN #{hilite}")
    
instance.grand
    instance
.spill_it
 
    
# see what gets changed if anything:
    
instance.alter_ego
 
    instance
.grand
    instance
.spill_it
    $log
.info("\n#{hilite} Testing instance of #{instance.class.name} END #{hilite}")
end
 
test
(SecondClass.new)
test(ThirdClass.new) 
Mobile_Guru Reviewed by Mobile_Guru on . Ruby class and instance variables lifecycle across inheritance require 'logger' $log = Logger.new(STDOUT) $log.level = Logger::INFO $log.progname = "LifecycleDemo" $log.formatter = proc { |severity, datetime, progname, msg| #"#{datetime.strftime("%Y-%b-%d %a %H:%M")} #{severity} #{progname} {#{msg}}\n" "#{msg}\n" } #$log.datetime_format = "%a %Y-%m-%d %H:%M" Rating: 5