Class: RuboCop::Cop::Rails::SafeNavigation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRubyVersion
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/safe_navigation.rb

Overview

Converts usages of ‘try!` to `&.`. It can also be configured to convert `try`. It will convert code to use safe navigation if the target Ruby version is set to 2.3+

Examples:

ConvertTry: false (default)

# bad
foo.try!(:bar)
foo.try!(:bar, baz)
foo.try!(:bar) { |e| e.baz }

foo.try!(:[], 0)

# good
foo.try(:bar)
foo.try(:bar, baz)
foo.try(:bar) { |e| e.baz }

foo&.bar
foo&.bar(baz)
foo&.bar { |e| e.baz }

ConvertTry: true

# bad
foo.try!(:bar)
foo.try!(:bar, baz)
foo.try!(:bar) { |e| e.baz }
foo.try(:bar)
foo.try(:bar, baz)
foo.try(:bar) { |e| e.baz }

# good
foo&.bar
foo&.bar(baz)
foo&.bar { |e| e.baz }

Constant Summary collapse

MSG =
'Use safe navigation (`&.`) instead of `%<try>s`.'
RESTRICT_ON_SEND =
%i[try try!].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.autocorrect_incompatible_withObject



54
55
56
# File 'lib/rubocop/cop/rails/safe_navigation.rb', line 54

def self.autocorrect_incompatible_with
  [Style::RedundantSelf]
end

Instance Method Details

#on_send(node) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/rails/safe_navigation.rb', line 58

def on_send(node)
  try_call(node) do |try_method, dispatch|
    return if try_method == :try && !cop_config['ConvertTry']
    return unless dispatch.sym_type? && dispatch.value.match?(/\w+[=!?]?/)

    add_offense(node, message: format(MSG, try: try_method)) do |corrector|
      autocorrect(corrector, node)
    end
  end
end