class RuboCop::Cop::Style::ModuleFunction
Checks for use of `extend self` or `module_function` in a module.
Supported styles are: module_function, extend_self, forbidden. `forbidden` style prohibits the usage of both styles.
NOTE: the cop won't be activated when the module contains any private methods.
@safety
Autocorrection is unsafe (and is disabled by default) because `extend self` and `module_function` do not behave exactly the same.
@example EnforcedStyle: module_function (default)
# bad module Test extend self # ... end # good module Test module_function # ... end
@example EnforcedStyle: module_function (default)
# good module Test extend self # ... private # ... end
@example EnforcedStyle: extend_self
# bad module Test module_function # ... end # good module Test extend self # ... end
@example EnforcedStyle: forbidden
# bad module Test module_function # ... end # bad module Test extend self # ... end # bad module Test extend self # ... private # ... end
Constants
- EXTEND_SELF_MSG
- FORBIDDEN_MSG
- MODULE_FUNCTION_MSG
Public Instance Methods
on_module(node)
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 90 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
Private Instance Methods
check_extend_self(nodes) { |node| ... }
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 127 def check_extend_self(nodes) nodes.each do |node| yield node if module_function_node?(node) end end
check_forbidden(nodes) { |node| ... }
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 133 def check_forbidden(nodes) nodes.each do |node| yield node if extend_self_node?(node) yield node if module_function_node?(node) end end
check_module_function(nodes) { |node| ... }
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 119 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
each_wrong_style(nodes, &block)
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 108 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
message(_range)
click to toggle source
# File lib/rubocop/cop/style/module_function.rb, line 140 def message(_range) return FORBIDDEN_MSG if style == :forbidden style == :module_function ? MODULE_FUNCTION_MSG : EXTEND_SELF_MSG end