Class: RuboCop::Cop::Codemod::KeepUnique

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
IgnoredNode
Defined in:
lib/rubocop/oneoff_codemod/cops/keep_unique.rb

Overview

KeepUnique

Constant Summary collapse

MSG =
"Keep array items unique, removing duplicates."
COMMAND =
"keep-unique"

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ KeepUnique

Returns a new instance of KeepUnique.



14
15
16
17
# File 'lib/rubocop/oneoff_codemod/cops/keep_unique.rb', line 14

def initialize(*args)
  super
  @commands = {}
end

Instance Method Details

#command_exists?(node) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/rubocop/oneoff_codemod/cops/keep_unique.rb', line 31

def command_exists?(node)
  @commands[node.location.line - 1] == COMMAND
end

#on_array(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rubocop/oneoff_codemod/cops/keep_unique.rb', line 35

def on_array(node)
  return unless command_exists? node
  return unless node.loc.begin.source == "[" || node.loc.begin.source.start_with?("%w")

  add_offense(node) do |corrector|
    next if part_of_ignored_node?(node)

    indent = " " * node.values.first.loc.column
    if node.loc.begin.source == "["
      separator = ", "
      line_separator = ",\n#{indent}"
    else
      separator = " "
      line_separator = "\n#{indent}"
    end

    content = []
    content << node.loc.begin.source
    content << processed_source.raw_source[node.loc.begin.end_pos..(node.values.first.loc.expression.begin_pos - 1)] # rubocop:disable Layout/LineLength

    acc = node.values.uniq(&:source).each_with_object([]) do |v_node, acc|
      acc << [] if acc.last&.last&.loc&.line != v_node.loc.line # rubocop:disable Style/SafeNavigationChainLength
      acc.last << v_node
    end
    content << acc.map { |a| a.map(&:source).join(separator) }.join(line_separator)

    content << processed_source.raw_source[node.values.last.loc.expression.end_pos..(node.loc.end.begin_pos - 1)] # rubocop:disable Layout/LineLength
    content << node.loc.end.source

    corrector.replace(node, content)
  end

  ignore_node(node)
end

#on_new_investigationObject



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rubocop/oneoff_codemod/cops/keep_unique.rb', line 19

def on_new_investigation
  processed_source.comments.each do |comment|
    next unless comment.text == "# @#{COMMAND}"

    @commands[comment.location.line] = COMMAND

    add_offense(comment.location.expression) do |corrector|
      corrector.replace(comment.location.expression, "#")
    end
  end
end