Class: RuboCop::Cop::Style::MapCompactWithConditionalBlock
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/style/map_compact_with_conditional_block.rb
Overview
Prefer ‘select` or `reject` over `map { … }.compact`.
Constant Summary collapse
- MSG =
'Replace `map { ... }.compact` with `%<method>s`.'
Constants inherited from Base
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods included from AutoCorrector
Methods inherited from Base
#active_support_extensions_enabled?, #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?, #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
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Instance Method Details
#map_and_compact?(node) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/rubocop/cop/style/map_compact_with_conditional_block.rb', line 46 def_node_matcher :map_and_compact?, <<~RUBY (send (block (send _ :map) (args $(arg _)) { (if $_ $(lvar _) {next nil?}) (if $_ {next nil?} $(lvar _)) (if $_ (next $(lvar _)) {next nil nil?}) (if $_ {next nil nil?} (next $(lvar _))) (begin { (if $_ next nil?) (if $_ nil? next) } $(lvar _)) (begin { (if $_ (next $(lvar _)) nil?) (if $_ nil? (next $(lvar _))) } (nil)) }) :compact) RUBY |
#on_send(node) ⇒ Object
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/rubocop/cop/style/map_compact_with_conditional_block.rb', line 72 def on_send(node) map_and_compact?(node) do |block_argument_node, condition_node, return_value_node| return unless returns_block_argument?(block_argument_node, return_value_node) return if condition_node.parent.elsif? method = truthy_branch?(return_value_node) ? 'select' : 'reject' range = range(node) add_offense(range, message: format(MSG, method: method)) do |corrector| corrector.replace( range, "#{method} { |#{block_argument_node.source}| #{condition_node.source} }" ) end end end |