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:
self,
::RuboCop::Cop::RangeHelp,
::RuboCop::Cop::Base,
::RuboCop::Cop::AutocorrectLogic,
::RuboCop::Cop::IgnoredNode,
::RuboCop::Util,
RuboCop::AST::Sexp
|
|
| 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.
Constant Summary
-
MSG =
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 29'Use `%<prefer>s` instead of `%<current>s`.' -
MSG_FOR_PERCENT_LITERALS =
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 30'Use `push` with elements as arguments without array brackets instead of `%<current>s`.' -
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/style/concat_array_literals.rb', line 32%i[concat].freeze
::RuboCop::Cop::Base - Inherited
DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::RangeHelp - Included
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 |
Class Method Summary
-
.autocorrect_incompatible_with
Style/MethodCallWithArgsParenthesesremoving the parentheses of thepush(…)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
| #active_support_extensions_enabled?, #always_autocorrect?, #config, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #disabled_autocorrect?, | |
| #preview? | Whether the user opted in to unstable behavior, with |
| #processed_source, #project_index, #string_literals_frozen_by_default?, #target_satisfies_all_gem_version_requirements? | |
::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 |
| #contextual_autocorrect_held_back? | When LSP is enabled or the |
Instance Method Summary
-
#on_csend(node)
Alias for #on_send.
-
#on_send(node)
(also: #on_csend)
rubocop:disable-next Metrics.
-
#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]. - #comment_in?(range) ⇒ Boolean private
- #offense_range(node) private
- #percent_literals_includes_only_basic_literals?(node) ⇒ Boolean private
- #preferred_method(node) private
- #rebuild_call(corrector, offense, replacement) private
- #remove_brackets(corrector, node) private
- #replace_selector(corrector, node) private
::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 |
| #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 |
| #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.
# 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 ].
# 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)
# 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.
# 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
# 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) = format(MSG, prefer: prefer, current: current) else = format(MSG_FOR_PERCENT_LITERALS, current: current) end else prefer = preferred_method(node) = format(MSG, prefer: prefer, current: current) end add_offense(offense, 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)
# 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