Class: RuboCop::Cop::Guardrails::NoNilSuppression
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Guardrails::NoNilSuppression
- Defined in:
- lib/rubocop/cop/guardrails/no_nil_suppression.rb
Overview
Bans the safe navigation operator (‘&.`) and `try`/`try!`.
Both mechanisms silently swallow ‘nil`, hiding the question that matters: can this actually be nil? If it can’t, drop the operator and let a ‘NoMethodError` surface the real bug. If it can, that’s a concept worth naming — use an explicit predicate or a method that describes what the nil case means.
Constant Summary collapse
- MSG_SAFE_NAV =
'Do not use safe navigation (`&.`). ' \ 'If `nil` is expected, use an explicit predicate (e.g. `present?`, `nil?`).'
- MSG_TRY =
'Do not use `%<method>s`. ' \ 'If `nil` is expected, use an explicit predicate (e.g. `present?`, `nil?`).'
Instance Method Summary collapse
Instance Method Details
#on_csend(node) ⇒ Object
34 35 36 |
# File 'lib/rubocop/cop/guardrails/no_nil_suppression.rb', line 34 def on_csend(node) add_offense(node, message: MSG_SAFE_NAV) end |
#on_send(node) ⇒ Object
38 39 40 41 42 |
# File 'lib/rubocop/cop/guardrails/no_nil_suppression.rb', line 38 def on_send(node) if %i[try try!].include?(node.method_name) add_offense(node, message: format(MSG_TRY, method: node.method_name)) end end |