class RuboCop::Cop::Chef::Style::NegatingOnlyIf

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

@example

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

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

Constants

MSG

Public Instance Methods

on_block(node) click to toggle source
# 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, message: MSG, severity: :refactor) do |corrector|
      corrector.replace(code, code.source.gsub(/^!/, ''))
      corrector.replace(only_if.source_range, 'not_if')
    end
  end
end