I am currently working through the Gregory Brown Ruby Best Practices book. Early on, he is talking about refactoring some functionality from helper methods on a related class, to some methods on module, then had the module extend self
.
Hadn't seen that before, after a quick google, found out that extend self
on a module lets methods defined on the module see each other, which makes sense.
Now, my question is when would you do something like this
module StyleParser extend self def process(text) ... end def style_tag?(text) ... end end
and then refer to it in tests with
@parser = Prawn::Document::Text::StyleParser
as opposed to something like this?
class StyleParser def self.process(text) ... end def self.style_tag?(text) ... end end
is it so that you can use it as a mixin? or are there other reasons I'm not seeing?
A class should be used for functionality that will require instantiation or that needs to keep track of state. A module can be used either as a way to mix functionality into multiple classes, or as a way to provide one-off features that don't need to be instantiated or to keep track of state. A class method could also be used for the latter.
With that in mind, I think the distinction lies in whether or not you really need a class. A class method seems more appropriate when you have an existing class that needs some singleton functionality. If what you're making consists only of singleton methods, it makes more sense to implement it as a module and access it through the module directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With