lib/rubocop/cop/performance/compare_with_block.rb in rubocop-0.51.0 vs lib/rubocop/cop/performance/compare_with_block.rb in rubocop-0.52.0
- old
+ new
@@ -6,28 +6,29 @@
# This cop identifies places where `sort { |a, b| a.foo <=> b.foo }`
# can be replaced by `sort_by(&:foo)`.
# This cop also checks `max` and `min` methods.
#
# @example
- # @bad
+ # # bad
# array.sort { |a, b| a.foo <=> b.foo }
# array.max { |a, b| a.foo <=> b.foo }
# array.min { |a, b| a.foo <=> b.foo }
# array.sort { |a, b| a[:foo] <=> b[:foo] }
#
- # @good
+ # # good
# array.sort_by(&:foo)
# array.sort_by { |v| v.foo }
# array.sort_by do |var|
# var.foo
# end
# array.max_by(&:foo)
# array.min_by(&:foo)
# array.sort_by { |a| a[:foo] }
class CompareWithBlock < Cop
- MSG = 'Use `%s_by%s` instead of ' \
- '`%s { |%s, %s| %s <=> %s }`.'.freeze
+ MSG = 'Use `%<compare_method>s_by%<instead>s` instead of ' \
+ '`%<compare_method>s { |%<var_a>s, %<var_b>s| %<str_a>s ' \
+ '<=> %<str_b>s }`.'.freeze
def_node_matcher :compare?, <<-PATTERN
(block
$(send _ {:sort :min :max})
(args (arg $_a) (arg $_b))
@@ -83,10 +84,11 @@
return false unless args_a.empty?
end
true
end
+ # rubocop:disable Metrics/MethodLength
def message(send, method, var_a, var_b, args)
compare_method = send.method_name
if method == :[]
key = args.first
instead = " { |a| a[#{key.source}] }"
@@ -95,13 +97,17 @@
else
instead = "(&:#{method})"
str_a = "#{var_a}.#{method}"
str_b = "#{var_b}.#{method}"
end
- format(MSG, compare_method, instead,
- compare_method, var_a, var_b,
- str_a, str_b)
+ format(MSG, compare_method: compare_method,
+ instead: instead,
+ var_a: var_a,
+ var_b: var_b,
+ str_a: str_a,
+ str_b: str_b)
end
+ # rubocop:enable Metrics/MethodLength
def compare_range(send, node)
range_between(send.loc.selector.begin_pos, node.loc.end.end_pos)
end
end