Two ways of extending a class by class methods


/ Published in: Ruby
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.