class RuboCop::Cop::Style::ModuleFunction
end
end
# …
class << self
module Test
# good
end
# …
private
# …
extend self
module Test
# bad
end
# …
extend self
module Test
# bad
end
# …
module_function
module Test
# bad
@example EnforcedStyle: forbidden
end
end
# …
class << self
module Test
# good
end
# …
extend self
module Test
# good
end
# …
module_function
module Test
# bad
@example EnforcedStyle: extend_self
end
end
# …
class << self
module Test
# good
end
# …
private
# …
extend self
module Test
# good
end
# …
module_function
module Test
# good
end
# …
extend self
module Test
# bad
@example EnforcedStyle: module_function (default)
and ‘module_function` do not behave exactly the same.
Autocorrection is unsafe (and is disabled by default) because `extend self`
@safety
contains any private methods
- in default mode (`module_function`), the cop won’t be activated when the module
- ‘forbidden` style prohibits the usage of both styles
A couple of things to keep in mind:
Supported styles are: `module_function` (default), `extend_self` and `forbidden`.
Checks for use of `extend self` or `module_function` in a module.
def check_extend_self(nodes)
def check_extend_self(nodes) nodes.each do |node| yield node if module_function_node?(node) end end
def check_forbidden(nodes)
def check_forbidden(nodes) nodes.each do |node| yield node if extend_self_node?(node) yield node if module_function_node?(node) end end
def check_module_function(nodes)
def check_module_function(nodes) return if nodes.any? { |node| private_directive?(node) } nodes.each do |node| yield node if extend_self_node?(node) end end
def each_wrong_style(nodes, &block)
def each_wrong_style(nodes, &block) case style when :module_function check_module_function(nodes, &block) when :extend_self check_extend_self(nodes, &block) when :forbidden check_forbidden(nodes, &block) end end
def message(_range)
def message(_range) return FORBIDDEN_MSG if style == :forbidden style == :module_function ? MODULE_FUNCTION_MSG : EXTEND_SELF_MSG end
def on_module(node)
def on_module(node) return unless node.body&.begin_type? each_wrong_style(node.body.children) do |child_node| add_offense(child_node) do |corrector| next if style == :forbidden if extend_self_node?(child_node) corrector.replace(child_node, 'module_function') else corrector.replace(child_node, 'extend self') end end end end