patternrubyMinor
Calling methods of another module from a module, from a class extending both?
Viewed 0 times
frommodulebothmethodsanothercallingclassextending
Problem
module A
def methodInA
# do stuff
methodInB
# do stuff
end
end
module B
def methodInB
puts "this is a B method!"
end
end
class C
extend A
extend B
def initialize
methodInA
end
end
c = new CI'm not feeling good about this. Is this a good idea in general? Any pointers as to where I can learn the best pattern for this?
Solution
Since inheritance and interface both has some problems of their own, high level languages like ruby, python supports a different way for organizing code- Mixin.
The code you have written involves mixin, you can see this as interface with implemented methods.When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.
Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
say we have a module for debugging. we want to use this in many classes and modules. we can just include this debug module to our classes and all methods for debugging will be added in the code as own method of our class.
see the code bellow:
The code you have written involves mixin, you can see this as interface with implemented methods.When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.
Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
say we have a module for debugging. we want to use this in many classes and modules. we can just include this debug module to our classes and all methods for debugging will be added in the code as own method of our class.
see the code bellow:
module Debugger
def log
#do stuff
puts "#{Time.now}: This is a log"
end
end
class C
include Debugger
def initialize
#do stuff
end
def run
#do stuff
log
end
end
c = C.new
c.runCode Snippets
module Debugger
def log
#do stuff
puts "#{Time.now}: This is a log"
end
end
class C
include Debugger
def initialize
#do stuff
end
def run
#do stuff
log
end
end
c = C.new
c.runContext
StackExchange Code Review Q#30909, answer score: 3
Revisions (0)
No revisions yet.