2021-03-11 19:13:27 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
module RuboCop
|
|
|
|
module Cop
|
2022-10-11 01:57:18 +05:30
|
|
|
class ProjectPathHelper < RuboCop::Cop::Base
|
|
|
|
extend RuboCop::Cop::AutoCorrector
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
MSG = 'Use short project path helpers without explicitly passing the namespace: ' \
|
|
|
|
'`foo_project_bar_path(project, bar)` instead of ' \
|
2021-04-29 21:17:54 +05:30
|
|
|
'`foo_namespace_project_bar_path(project.namespace, project, bar)`.'
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
METHOD_NAME_PATTERN = /\A([a-z_]+_)?namespace_project(?:_[a-z_]+)?_(?:url|path)\z/.freeze
|
|
|
|
|
|
|
|
def on_send(node)
|
|
|
|
return unless method_name(node).to_s =~ METHOD_NAME_PATTERN
|
|
|
|
|
|
|
|
namespace_expr, project_expr = arguments(node)
|
|
|
|
return unless namespace_expr && project_expr
|
|
|
|
|
|
|
|
return unless namespace_expr.type == :send
|
|
|
|
return unless method_name(namespace_expr) == :namespace
|
|
|
|
return unless receiver(namespace_expr) == project_expr
|
|
|
|
|
2022-10-11 01:57:18 +05:30
|
|
|
add_offense(node.loc.selector) do |corrector|
|
|
|
|
helper_name = method_name(node).to_s.sub('namespace_project', 'project')
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2022-10-11 01:57:18 +05:30
|
|
|
arguments = arguments(node)
|
|
|
|
arguments.shift # Remove namespace argument
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2022-10-11 01:57:18 +05:30
|
|
|
replacement = "#{helper_name}(#{arguments.map(&:source).join(', ')})"
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
corrector.replace(node.source_range, replacement)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def receiver(node)
|
|
|
|
node.children[0]
|
|
|
|
end
|
|
|
|
|
|
|
|
def method_name(node)
|
|
|
|
node.children[1]
|
|
|
|
end
|
|
|
|
|
|
|
|
def arguments(node)
|
2022-01-26 12:08:38 +05:30
|
|
|
node.children[2..]
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|