Class: RuboCop::Cop::Lint::HashNewWithKeywordArgumentsAsDefault
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default.rb
Overview
Checks for the deprecated use of keyword arguments as a default in ‘Hash.new`.
This usage raises a warning in Ruby 3.3 and results in an error in Ruby 3.4. In Ruby 3.4, keyword arguments will instead be used to change the behavior of a hash. For example, the capacity option can be passed to create a hash with a certain size if you know it in advance, for better performance.
NOTE: The following corner case may result in a false negative when upgrading from Ruby 3.3 or earlier, but it is intentionally not detected to respect the expected usage in Ruby 3.4.
- source,ruby
Hash.new(capacity: 42)
Constant Summary collapse
- MSG =
'Use a hash literal instead of keyword arguments.'
- RESTRICT_ON_SEND =
%i[new].freeze
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, #always_autocorrect?, autocorrect_incompatible_with, badge, #begin_investigation, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #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, #parser_engine, #ready, #relevant_file?, requires_gem, #string_literals_frozen_by_default?, 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
#hash_new(node) ⇒ Object
36 37 38 |
# File 'lib/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default.rb', line 36 def_node_matcher :hash_new, <<~PATTERN (send (const {nil? (cbase)} :Hash) :new $[hash !braces?]) PATTERN |
#on_send(node) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default.rb', line 40 def on_send(node) return unless (first_argument = hash_new(node)) if first_argument.pairs.one? key = first_argument.pairs.first.key return if key.respond_to?(:value) && key.value == :capacity end add_offense(first_argument) do |corrector| corrector.wrap(first_argument, '{', '}') end end |