Skip to content

Commit

Permalink
Minor refactor of Style/RedundantSort.
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis authored and bbatsov committed Sep 28, 2021
1 parent 5b9899f commit 14ca0ce
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions lib/rubocop/cop/style/redundant_sort.rb
Expand Up @@ -102,37 +102,39 @@ class RedundantSort < Base
MATCHER

def on_send(node)
if (sort_node, sorter, accessor = redundant_sort?(node.parent))
ancestor = node.parent
elsif (sort_node, sorter, accessor = redundant_sort?(node.parent&.parent))
ancestor = node.parent.parent
else
return
end
ancestor, sort_node, sorter, accessor =
find_redundant_sort(node.parent, node.parent&.parent)
return unless ancestor

register_offense(ancestor, sort_node, sorter, accessor)
end

private

def register_offense(ancestor, sort_node, sorter, accessor)
message = message(ancestor, sorter, accessor)

add_offense(offense_range(sort_node, ancestor), message: message) do |corrector|
autocorrect(corrector, ancestor, sort_node, sorter, accessor)
def find_redundant_sort(*nodes)
nodes.each do |node|
if (sort_node, sorter, accessor = redundant_sort?(node))
return [node, sort_node, sorter, accessor]
end
end

nil
end

def autocorrect(corrector, node, sort_node, sorter, accessor)
# Remove accessor, e.g. `first` or `[-1]`.
corrector.remove(range_between(accessor_start(node), node.loc.expression.end_pos))
def register_offense(node, sort_node, sorter, accessor)
message = message(node, sorter, accessor)

add_offense(offense_range(sort_node, node), message: message) do |corrector|
# Remove accessor, e.g. `first` or `[-1]`.
corrector.remove(range_between(accessor_start(node), node.loc.expression.end_pos))

# Replace "sort" or "sort_by" with the appropriate min/max method.
corrector.replace(sort_node.loc.selector, suggestion(sorter, accessor, arg_value(node)))
# Replace "sort" or "sort_by" with the appropriate min/max method.
corrector.replace(sort_node.loc.selector, suggestion(sorter, accessor, arg_value(node)))
end
end

def offense_range(sort_node, ancestor)
range_between(sort_node.loc.selector.begin_pos, ancestor.loc.expression.end_pos)
def offense_range(sort_node, node)
range_between(sort_node.loc.selector.begin_pos, node.loc.expression.end_pos)
end

def message(node, sorter, accessor)
Expand Down

0 comments on commit 14ca0ce

Please sign in to comment.