2018-08-24 18:08:34 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
2018-08-27 08:23:25 -04:00
|
|
|
# Enforces the use of 'class_methods' instead of 'module ClassMethods' for activesupport concerns.
|
2019-09-18 10:02:45 -04:00
|
|
|
# For more information see: https://gitlab.com/gitlab-org/gitlab-foss/issues/50414
|
2018-08-24 18:08:34 -04:00
|
|
|
#
|
|
|
|
# @example
|
|
|
|
# # bad
|
|
|
|
# module Foo
|
2018-08-27 08:23:25 -04:00
|
|
|
# extend ActiveSupport::Concern
|
|
|
|
#
|
2018-08-24 18:08:34 -04:00
|
|
|
# module ClassMethods
|
|
|
|
# def a_class_method
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# # good
|
|
|
|
# module Foo
|
2018-08-27 08:23:25 -04:00
|
|
|
# extend ActiveSupport::Concern
|
|
|
|
#
|
2018-08-24 18:08:34 -04:00
|
|
|
# class_methods do
|
|
|
|
# def a_class_method
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
2022-09-14 11:12:56 -04:00
|
|
|
class PreferClassMethodsOverModule < RuboCop::Cop::Base
|
|
|
|
extend RuboCop::Cop::AutoCorrector
|
2018-08-24 18:08:34 -04:00
|
|
|
include RangeHelp
|
|
|
|
|
|
|
|
MSG = 'Do not use module ClassMethods, use class_methods block instead.'
|
|
|
|
|
2018-08-27 08:23:25 -04:00
|
|
|
def_node_matcher :extend_activesupport_concern?, <<~PATTERN
|
|
|
|
(:send nil? :extend (:const (:const nil? :ActiveSupport) :Concern))
|
|
|
|
PATTERN
|
|
|
|
|
2018-08-24 18:08:34 -04:00
|
|
|
def on_module(node)
|
2022-09-14 11:12:56 -04:00
|
|
|
return unless class_methods_module_in_activesupport_concern?(node)
|
2018-08-24 18:08:34 -04:00
|
|
|
|
2022-09-14 11:12:56 -04:00
|
|
|
add_offense(node) do |corrector|
|
2018-08-24 18:08:34 -04:00
|
|
|
corrector.replace(module_range(node), 'class_methods do')
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2022-09-14 11:12:56 -04:00
|
|
|
def class_methods_module_in_activesupport_concern?(node)
|
|
|
|
node.defined_module_name == 'ClassMethods' &&
|
|
|
|
module_extends_activesupport_concern?(node)
|
|
|
|
end
|
|
|
|
|
2018-08-28 10:02:48 -04:00
|
|
|
def module_extends_activesupport_concern?(node)
|
2018-08-28 04:58:36 -04:00
|
|
|
container_module = container_module_of(node)
|
2018-08-27 09:24:11 -04:00
|
|
|
return false unless container_module
|
|
|
|
|
|
|
|
container_module.descendants.any? do |descendant|
|
2018-08-27 08:23:25 -04:00
|
|
|
extend_activesupport_concern?(descendant)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-08-27 09:24:11 -04:00
|
|
|
def container_module_of(node)
|
2018-08-28 04:58:36 -04:00
|
|
|
while node = node.parent
|
|
|
|
break if node.type == :module
|
|
|
|
end
|
2018-08-27 08:23:25 -04:00
|
|
|
|
|
|
|
node
|
|
|
|
end
|
|
|
|
|
2018-08-24 18:08:34 -04:00
|
|
|
def module_range(node)
|
|
|
|
module_node, _ = *node
|
|
|
|
range_between(node.loc.keyword.begin_pos, module_node.source_range.end_pos)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|