Posted By

Shamaoke on 12/28/10


Tagged

class extending


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

WaxWing


Two ways of extending a class by class methods


 / Published in: Ruby
 

An example which illustrates the ways of extending a class by class methods.

  1. # encoding: utf-8
  2.  
  3. # Two ways of extending a class by class methods.
  4. module M
  5. module ClassMethods
  6. def one
  7. 'ok!'
  8. end
  9.  
  10. def two
  11. 'ok two!'
  12. end
  13. end
  14. end
  15.  
  16. # I
  17. class TestOne
  18. class << self
  19. include M::ClassMethods
  20. end
  21. end
  22.  
  23. # II
  24. class TestTwo
  25. extend M::ClassMethods
  26. end
  27.  
  28. puts [
  29. TestOne.one, #=> ok!
  30. TestOne.two #=> ok two!
  31. ]
  32.  
  33. puts [
  34. TestTwo.one, #=> ok!
  35. TestTwo.two #=> ok two!
  36. ]

Report this snippet  

You need to login to post a comment.