Class: RuboCop::Cop::Homebrew::Present

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
rubocops/present.rb

Overview

Checks for code that can be written with simpler conditionals using Object#present?.

Examples:

# Converts usages of `!nil? && !empty?` to `present?`

# bad
!foo.nil? && !foo.empty?

# bad
foo != nil && !foo.empty?

# good
foo.present?

Constant Summary collapse

MSG_EXISTS_AND_NOT_EMPTY =
"Use `%<prefer>s` instead of `%<current>s`."

Instance Method Summary collapse

Instance Method Details

#autocorrect(corrector, node) ⇒ Object



62
63
64
65
66
# File 'rubocops/present.rb', line 62

def autocorrect(corrector, node)
  variable1, _variable2 = exists_and_not_empty?(node)
  range = node.source_range
  corrector.replace(range, replacement(variable1))
end

#on_and(node) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'rubocops/present.rb', line 40

def on_and(node)
  exists_and_not_empty?(node) do |var1, var2|
    return if var1 != var2

    message = format(MSG_EXISTS_AND_NOT_EMPTY, prefer: replacement(var1), current: node.source)

    add_offense(node, message: message) do |corrector|
      autocorrect(corrector, node)
    end
  end
end

#on_or(node) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'rubocops/present.rb', line 52

def on_or(node)
  exists_and_not_empty?(node) do |var1, var2|
    return if var1 != var2

    add_offense(node, message: MSG_EXISTS_AND_NOT_EMPTY) do |corrector|
      autocorrect(corrector, node)
    end
  end
end