Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. # Patch method will always defer to any pre-defined method of same name,
  2. # only use Patch implementation if method not already defined.
  3. # An error could still occur if the pre-defined method expects a different
  4. # number of parameters.
  5. # By defining in a module rather than direct patching of the class, the
  6. # patch method won't even be used if method already defined directly as an
  7. # instance method on the class (i.e. not from some other mix-in module).
  8.  
  9. module Patch
  10. def a_method(x, y, z)
  11. return super(x, y, z) if defined? super
  12. x * y * z
  13. end
  14. end
  15.  
  16. module Mixin
  17. def a_method(x, y, z)
  18. return x + y + z
  19. end
  20. end
  21.  
  22. class A
  23. def a_method(x, y, z)
  24. return x + y + z
  25. end
  26. end
  27.  
  28. class B
  29. include Mixin
  30. end
  31.  
  32. class C
  33. end
  34.  
  35. A.send :include, Patch
  36. B.send :include, Patch
  37. C.send :include, Patch
  38.  
  39. puts A.new.a_method(2, 3, 4) # 2 + 3 + 4 = 9 -- use method defined in class
  40. puts B.new.a_method(2, 3, 4) # 2 + 3 + 4 = 9 -- delegate to method from Mixin
  41. puts C.new.a_method(2, 3, 4) # 2 * 3 * 4 = 24 -- use method from Patch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement