Class: RuboCop::Cop::Style::MapToHash
- Extended by:
- AutoCorrector, TargetRubyVersion
- Includes:
- RangeHelp
- Defined in:
- lib/rubocop/cop/style/map_to_hash.rb
Overview
Looks for uses of map.to_h
or collect.to_h
that could be
written with just to_h
in Ruby >= 2.6.
Note
|
Style/HashTransformKeys and Style/HashTransformValues will
also change this pattern if only hash keys or hash values are being
transformed.
|
Constant Summary collapse
- MSG =
'Pass a block to `to_h` instead of calling `%<method>s.to_h`.'
- RESTRICT_ON_SEND =
%i[to_h].freeze
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods included from AutoCorrector
Methods included from TargetRubyVersion
minimum_target_ruby_version, required_minimum_ruby_version, support_target_ruby_version?
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
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_to_h?(node) ⇒ Object
41 42 43 44 45 46 |
# File 'lib/rubocop/cop/style/map_to_hash.rb', line 41 def_node_matcher :map_to_h?, <<~PATTERN { $(send ({block numblock} $(send _ {:map :collect}) ...) :to_h) $(send $(send _ {:map :collect} (block_pass sym)) :to_h) } PATTERN |
#on_send(node) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/rubocop/cop/style/map_to_hash.rb', line 48 def on_send(node) return unless (to_h_node, map_node = map_to_h?(node)) = format(MSG, method: map_node.loc.selector.source) add_offense(map_node.loc.selector, message: ) do |corrector| # If the `to_h` call already has a block, do not autocorrect. next if to_h_node.block_node autocorrect(corrector, to_h_node, map_node) end end |