Posted By

Shamaoke on 03/10/11


Tagged

class ruby configuration


Versions (?)

Configure some behaviour through a separete configuration class


 / Published in: Ruby
 

  1. # encoding = utf-8
  2.  
  3. # Lib
  4. module ObjectExtensions
  5. def execute(&block)
  6. Extension.new.execute(&block)
  7. end
  8. end
  9.  
  10. class Parent
  11. @@config = []
  12. end
  13.  
  14. class Extension < Parent
  15. def execute(&block)
  16. self.instance_eval(&block)
  17. end
  18.  
  19. def one; puts @@config[0] end
  20. def two; puts @@config[1] end
  21. def three; puts @@config[2] end
  22. end
  23.  
  24. Object.__send__(:include, ObjectExtensions)
  25.  
  26. class Config < Parent
  27. class << self
  28. def init
  29. yield self
  30. end
  31.  
  32. def one
  33. @@config << 'one'
  34. end
  35.  
  36. def two
  37. @@config << 'two'
  38. end
  39.  
  40. def three
  41. @@config << 'three'
  42. end
  43. end
  44. end
  45.  
  46. # Configurating
  47. Config.init do |c|
  48. c.one #=> set @@config[0] to 'one'
  49. c.two #=> set @@config[1] to 'two'
  50. c.three #=> set @@config[2] to 'three'
  51. end
  52.  
  53. # Usage
  54. execute do
  55. one #=> one
  56. two #=> two
  57. three #=> three
  58. end

Report this snippet  

You need to login to post a comment.