Class: RuboCop::Cop::Chef::Style::NegatingOnlyIf

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/chef/style/negating_only_if.rb

Overview

Instead of using only_if conditionals with ! to negate the returned value, use not_if which is easier to read

Examples:


### incorrect
package 'legacy-sysv-deps' do
  only_if { !systemd }
end

### correct
package 'legacy-sysv-deps' do
  not_if { systemd }
end

Constant Summary collapse

MSG =
'Instead of using only_if conditionals with ! to negate the returned value, use not_if which is easier to read'

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_block(node) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rubocop/cop/chef/style/negating_only_if.rb', line 49

def on_block(node)
  negated_only_if?(node) do |only_if, code|
    # skip inspec controls where we don't have not_if
    return if node.parent&.parent&.block_type? &&
              node.parent&.parent&.method_name == :control

    # the value was double negated to work around types: ex: !!systemd?
    return if code.descendants.first.send_type? &&
              code.descendants.first.negation_method?

    add_offense(node, severity: :refactor) do |corrector|
      corrector.replace(code, code.source.gsub(/^!/, ''))
      corrector.replace(only_if.source_range, 'not_if')
    end
  end
end