Class: RuboCop::Cop::Operandi::PreferOptionalOverDefaultNil
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Operandi::PreferOptionalOverDefaultNil
- Extended by:
- AutoCorrector
- Defined in:
- lib/operandi/rubocop/cop/operandi/prefer_optional_over_default_nil.rb
Overview
Detects when default: nil is used instead of optional: true.
Using optional: true is the preferred way to indicate an optional field
with no default value.
Constant Summary collapse
- MSG =
"Prefer `optional: true` over `default: nil` for `%<name>s`."- MSG_REDUNDANT =
"`default: nil` is redundant when `optional: true` is specified for `%<name>s`."- RESTRICT_ON_SEND =
[:arg, :output].freeze
Instance Method Summary collapse
Instance Method Details
#field_call?(node) ⇒ Object
37 38 39 |
# File 'lib/operandi/rubocop/cop/operandi/prefer_optional_over_default_nil.rb', line 37 def_node_matcher :field_call?, <<~PATTERN (send nil? {:arg :output} (sym $_) ...) PATTERN |
#on_send(node) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/operandi/rubocop/cop/operandi/prefer_optional_over_default_nil.rb', line 41 def on_send(node) field_call?(node) do |name| default_nil_pair = find_default_nil_pair(node) return unless default_nil_pair optional_pair = find_optional_true_pair(node) if optional_pair # Both optional: true and default: nil - remove default: nil add_offense(node, message: format(MSG_REDUNDANT, name: name)) do |corrector| remove_hash_pair(corrector, node.arguments[1], default_nil_pair) end else # Only default: nil - replace with optional: true add_offense(node, message: format(MSG, name: name)) do |corrector| corrector.replace(default_nil_pair.source_range, "optional: true") end end end end |