Why someone prefer to define class method as `module SomeModule extend self` but not `class SomeClass ; def self.method`?
I am writing Ruby code.
The code before refactoring looks like:
class Tool
def self.say_hi
return "hi"
end
end
and after refactored by my workmates:
module Tool
extend self
def say_hi
return "hi"
end
end
both style of code can work as: Tool.say_hi
.
I want to know what's the pros and cons for his style. thanks.
They have changed the class for a module, the main difference is that modules can be included in other class to reuse that say_hi
method.
class Toolbox
include Tool
end
Toolbox.new.say_hi
But I don't know if that was the main driver for the refactor, another difference between the two approaches is that you can control the visibility of the method with the second snippet.
module Tool
extend self
private
def say_hi
return "hi"
end
end
Tool.say_hi
Will return private method 'say_hi' called for Tool:Module (NoMethodError
meanwhile this would just work.
class Tool
private
def self.say_hi
return "hi"
end
end
Tool.say_hi