Class: RuboCop::Cop::Style::MapToSet

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/style/map_to_set.rb

Overview

Looks for uses of map.to_set or collect.to_set that could be written with just to_set.

Examples:

# bad
something.map { |i| i * 2 }.to_set

# good
something.to_set { |i| i * 2 }

# bad
[1, 2, 3].collect { |i| i.to_s }.to_set

# good
[1, 2, 3].to_set { |i| i.to_s }

Cop Safety Information:

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

Constant Summary collapse

MSG =
'Pass a block to `to_set` instead of calling `%<method>s.to_set`.'
RESTRICT_ON_SEND =
%i[to_set].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, autocorrect_incompatible_with, badge, #begin_investigation, callbacks_needed, #callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, cop_name, #cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

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

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

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

Instance Method Details

#map_to_set?(node) ⇒ Object



34
35
36
37
38
39
# File 'lib/rubocop/cop/style/map_to_set.rb', line 34

def_node_matcher :map_to_set?, <<~PATTERN
  {
    $(send ({block numblock} $(send _ {:map :collect}) ...) :to_set)
    $(send $(send _ {:map :collect} (block_pass sym)) :to_set)
  }
PATTERN

#on_send(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/style/map_to_set.rb', line 41

def on_send(node)
  return unless (to_set_node, map_node = map_to_set?(node))

  message = format(MSG, method: map_node.loc.selector.source)
  add_offense(map_node.loc.selector, message: message) do |corrector|
    # If the `to_set` call already has a block, do not autocorrect.
    next if to_set_node.block_node

    autocorrect(corrector, to_set_node, map_node)
  end
end