Class: RuboCop::Cop::Style::CollectionCompact
- Extended by:
- AutoCorrector
- Includes:
- RangeHelp
- Defined in:
- lib/rubocop/cop/style/collection_compact.rb
Overview
This cop checks for places where custom logic on rejection nils from arrays and hashes can be replaced with ‘Array,Hash#compact,compact!`.
Constant Summary collapse
- MSG =
'Use `%<good>s` instead of `%<bad>s`.'
- RESTRICT_ON_SEND =
i[reject reject! select select!].freeze
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods included from AutoCorrector
Methods inherited from Base
#add_global_offense, #add_offense, autocorrect_incompatible_with, badge, 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, 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
Methods included from AutocorrectLogic
#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?
Methods included from IgnoredNode
#ignore_node, #ignored_node?, #part_of_ignored_node?
Methods included from Util
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Instance Method Details
#on_send(node) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/rubocop/cop/style/collection_compact.rb', line 61 def on_send(node) block_node = node.parent return unless block_node&.block_type? return unless (method_name, args, receiver = reject_method?(block_node) || select_method?(block_node)) return unless args.last.source == receiver.source range = offense_range(node, block_node) good = good_method_name(method_name) = format(MSG, good: good, bad: range.source) add_offense(range, message: ) { |corrector| corrector.replace(range, good) } end |
#reject_method?(node) ⇒ Object
41 42 43 44 45 46 47 48 |
# File 'lib/rubocop/cop/style/collection_compact.rb', line 41 def_node_matcher :reject_method?, "(block\n (send\n _ ${:reject :reject!})\n $(args ...)\n (send\n $(lvar _) :nil?))\n" |
#select_method?(node) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/rubocop/cop/style/collection_compact.rb', line 51 def_node_matcher :select_method?, "(block\n (send\n _ ${:select :select!})\n $(args ...)\n (send\n (send\n $(lvar _) :nil?) :!))\n" |