Posted By

m1b on 08/18/11


Tagged

ruby logging inheritance features


Versions (?)

Ruby class and instance variables lifecycle across inheritance demo


 / Published in: Ruby
 

  1. require 'logger'
  2. $log = Logger.new(STDOUT)
  3. $log.level = Logger::INFO
  4. $log.progname = "LifecycleDemo"
  5. $log.formatter = proc { |severity, datetime, progname, msg|
  6. #"#{datetime.strftime("%Y-%b-%d %a %H:%M")} #{severity} #{progname} {#{msg}}\n"
  7. "#{msg}\n"
  8. }
  9. #$log.datetime_format = "%a %Y-%m-%d %H:%M"
  10.  
  11.  
  12. class FirstClass
  13. @@grandClass = "FirstClassVar" # class level variable to track
  14. def initialize
  15. @grandVar = "FirstInstanceVar" # instance variable to track
  16. $log.info("! FirstClass init, #{ids}")
  17. end
  18. def grand
  19. $log.info("> FirstClass grand, #{ids}")
  20. end
  21.  
  22. def ids
  23. "#{self.class.name}:: #{@@grandClass}:#{@@grandClass.object_id}, #{@grandVar}:#{@grandVar.object_id}"
  24. end
  25. end
  26.  
  27. class SecondClass < FirstClass
  28. def initialize
  29. @ego_hilite = "-" * 15
  30. super
  31. $log.info("! Second class init, #{ids}")
  32. end
  33. def spill_it
  34. $log.info("> Spill It call, #{ids}")
  35. end
  36. def alter_ego
  37. @grandVar = "SecondInstanceVar"
  38. @@grandClass = "SecondClassVar"
  39. $log.info("\n#{@ego_hilite} Ego altered by the #{self.class.name} #{@ego_hilite}\n\n")
  40. end
  41. end
  42.  
  43. class ThirdClass < SecondClass
  44. @@grandClass = "ThirdClassStatic"
  45. def initialize
  46. super
  47. $log.info("! 3rd class init, #{ids}")
  48. end
  49. def alter_ego
  50. @grandVar = "ThirdInstanceVar"
  51. @@grandClass = "ThirdClassVar"
  52. $log.info("\n#{@ego_hilite} Ego altered by the Third Class #{@ego_hilite}\n")
  53. end
  54. end
  55.  
  56. def test(instance)
  57. hilite = "*" * 20
  58. $log.info("\n\n#{hilite} Testing instance of #{instance.class.name} BEGIN #{hilite}")
  59. instance.grand
  60. instance.spill_it
  61.  
  62. # see what gets changed if anything:
  63. instance.alter_ego
  64.  
  65. instance.grand
  66. instance.spill_it
  67. $log.info("\n#{hilite} Testing instance of #{instance.class.name} END #{hilite}")
  68. end
  69.  
  70. test(SecondClass.new)
  71. test(ThirdClass.new)

Report this snippet  

You need to login to post a comment.