From: Zouplaz Date: 2008-10-11T15:22:33+09:00 Subject: Re: Help me to better understand modules le 10/10/2008 21:56, Brian Candler nous a dit: > > Your code is trying to do both. To change it into the mixin style you > would write: > > module Payment > def method_payment > p 'here again' > end > end > > module SpecificPayment > def my_stuff > p 'here' > method_payment > end > end > > class AClass > include Payment > include SpecificPayment > > def go > my_stuff > method_payment > end > end > > a = AClass.new > a.go > Thank you Brian, for this very valuable explanation - It's very clear to me now. I've noticed that, with the self. version I need to prefix them with the module's name, so having namespacing which tends to make the code more readable. module Payment def self.method_payment end end class AClass include Payment def go Payment.method_payment() end end > > I typically find that object composition ("has-a") rather than > subclassing ("is-a" or mixin) is the most flexible way to compose > systems. Obviously the component classes are easy to test inisolation, > and they tend to be easier to re-use. > Yes, I agree - May be very conventional too but easy to understand, to read and furthermore to isolate as you point out > > Some people's immediate reaction would be: "but that creates a new > object for every controller action invocation!". Ignore them. That is > premature optimisation; object creation is cheap in Ruby. Consider: > > 10.times { puts "hello" } > > This creates 10 separate string objects, but nobody complains (much) > about that. You win one dollar ;-) This is the first reason that pushed me to have a look to modules for my current project, instead of using composite objects (composite controller class in that case) > > If the right conceptual model is for a payment-handler class, which > carries its own state, then do that. > > Of course, if SpecificPayment.my_stuff() and Payment.method_payment() > are "pure" module methods, depending only on values passed as arguments, > then by all means keep them that way. > I've switched from Class to Module - was quite interesting to compare the two solutions but I prefer the class method and will switch back to that because I feel more confortable with it Now I see situations where modules will be very usefull but for the current case it give nothing more compared to the class approach. Btw, the modules methods proved to be stubbable very easily... > Hope that gives you something to think about :-) I learned a lot today ;-) Thank you