Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. class A
  2. def initialize(add_module)
  3. self.class.send(:include, MM::NN) if add_module
  4. end
  5. end
  6.  
  7. module MM::NN
  8. def display
  9. puts "module method called"
  10. end
  11. end
  12.  
  13. A.new(true).display #module method called
  14. A.new(false).display #NoMethodError
  15.  
  16. A.new(true).display #module method called
  17. A.new(false).display #NoMethodError
  18.  
  19. A.new(false).display #NoMethodError
  20. A.new(true).display #module method called
  21.  
  22. module TestModule
  23. def test_method; "ok"; end
  24. end
  25.  
  26. class A
  27. def initialize(add_module)
  28. singleton_class.include(TestModule) if add_module
  29. end
  30. end
  31.  
  32. A.new(true).test_method # module method called
  33. A.new(false).test_method # NoMethodError
  34.  
  35. class A
  36. def initialize(add_module)
  37. extend(MM::NN) if add_module
  38. end
  39. end
  40.  
  41. class A
  42. def initialize(add_module)
  43. if add_module
  44. (class <<self; include MM::NN; end)
  45. end
  46. end
  47. end
  48.  
  49. # This class is here because I'm assuming you can't make `MM::NN` a class in its own right. However it probably needs additional data or methods to actually work with the MM::NN methods
  50. class NN_implementation
  51. include MM::NN
  52. end
  53.  
  54. class A
  55. def initialize(use_module)
  56. # if this class needs access to data or methods from A, you could add `self` as an input arg to the constructor of `NN_implementation`
  57. @nn = NN_implmenetation.new if use_module
  58. end
  59.  
  60. def has_nn?
  61. !@nn.blank?
  62. end
  63. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement