123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::ConcatArrayLiterals

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/concat_array_literals.rb

Overview

Enforces the use of Array#push(item) instead of Array#concat([item]) to avoid redundant array literals.

Examples:

# bad
list.concat([foo])
list.concat([bar, baz])
list.concat([qux, quux], [corge])

# good
list.push(foo)
list.push(bar, baz)
list.push(qux, quux, corge)

Cop Safety Information:

  • This cop is unsafe, as it can produce false positives if the receiver is not an Array object.

Constant Summary

::RuboCop::Cop::Base - Inherited

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

  • .autocorrect_incompatible_with

    Style/MethodCallWithArgsParentheses removing the parentheses of the push(…​) this cop writes in the same pass drops the line continuation a multiline call needs.

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

::RuboCop::Cop::Base - Inherited

::RuboCop::Cop::AutocorrectLogic - Included

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?,
#skipped_unsafe_correction_with_disable_uncorrectable?

Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while --disable-uncorrectable asks for a todo comment on everything this run cannot correct.

#contextual_autocorrect_held_back?

When LSP is enabled or the --editor-mode option is on, it is considered as editing source code, and autocorrection with AutoCorrect: contextual will not be performed.

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos

rubocop:disable-next Metrics/ParameterLists.

#move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed

 — grouped under the Commissioner heading above.

#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked).

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Class Method Details

.autocorrect_incompatible_with

Style/MethodCallWithArgsParentheses removing the parentheses of the push(…​) this cop writes in the same pass drops the line continuation a multiline call needs. Style/TrailingCommaInArguments adds a comma after the array literal this cop replaces with its elements in the same pass.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 38

def self.autocorrect_incompatible_with
  [Style::MethodCallWithArgsParentheses, Style::TrailingCommaInArguments]
end

Instance Method Details

#closing_bracket_range(node, argument) (private)

Whatever sits between the last element and the ] of an array that isn’t the last argument would end up before the following comma (a newline before it is a syntax error), so it’s removed along with the ].

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 132

def closing_bracket_range(node, argument)
  return argument.loc.end if argument.equal?(node.last_argument)

  range_between(argument.children.last.source_range.end_pos, argument.loc.end.end_pos)
end

#comment_in?(range) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 110

def comment_in?(range)
  processed_source.each_comment_in_lines(range.line..range.last_line).any? do |comment|
    range.contains?(comment.source_range)
  end
end

#offense_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 80

def offense_range(node)
  node.loc.selector.join(node.source_range.end)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 76

alias on_csend on_send

#on_send(node) Also known as: #on_csend

rubocop:disable-next Metrics

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 43

def on_send(node)
  return if node.arguments.empty?
  return unless node.arguments.all?(&:array_type?)

  offense = offense_range(node)
  current = offense.source

  if (use_percent_literal = node.arguments.any?(&:percent_literal?))
    if percent_literals_includes_only_basic_literals?(node)
      prefer = preferred_method(node)
      message = format(MSG, prefer: prefer, current: current)
    else
      message = format(MSG_FOR_PERCENT_LITERALS, current: current)
    end
  else
    prefer = preferred_method(node)
    message = format(MSG, prefer: prefer, current: current)
  end

  add_offense(offense, message: message) do |corrector|
    if use_percent_literal
      next unless prefer

      rebuild_call(corrector, offense, prefer)
    elsif node.arguments.any? { |argument| argument.children.empty? }
      # In-place bracket removal would leave dangling commas (e.g.
      # `concat([], [b])` -> `push(, b)`), so rebuild the call instead.
      rebuild_call(corrector, offense, preferred_method(node))
    else
      remove_brackets(corrector, node)
    end
  end
end

#percent_literals_includes_only_basic_literals?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 97

def percent_literals_includes_only_basic_literals?(node)
  node.arguments.select(&:percent_literal?).all? do |arg|
    arg.children.all? { |child| child.type?(:str, :sym) }
  end
end

#preferred_method(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 84

def preferred_method(node)
  new_arguments =
    node.arguments.flat_map do |arg|
      if arg.percent_literal?
        arg.children.map { |child| child.value.inspect }
      else
        arg.children.map(&:source)
      end
    end.join(', ')

  "push(#{new_arguments})"
end

#rebuild_call(corrector, offense, replacement) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 103

def rebuild_call(corrector, offense, replacement)
  # The comments inside the call would be lost.
  return if comment_in?(offense)

  corrector.replace(offense, replacement)
end

#remove_brackets(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 116

def remove_brackets(corrector, node)
  closing_ranges = node.arguments.map { |argument| closing_bracket_range(node, argument) }
  # A comment or a heredoc body there can't be moved out of the way.
  return unless closing_ranges.all? { |range| range.source.match?(/\A[\s,]*\]\z/) }

  replace_selector(corrector, node)

  node.arguments.zip(closing_ranges) do |argument, closing_range|
    corrector.remove(argument.loc.begin)
    corrector.remove(closing_range)
  end
end

#replace_selector(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 138

def replace_selector(corrector, node)
  if node.parenthesized? || node.single_line?
    corrector.replace(node.loc.selector, 'push')
  else
    range = node.loc.selector.join(node.first_argument.source_range.begin)

    corrector.replace(range, 'push(')
    corrector.insert_after(node.last_argument.loc.end, ')')
  end
end