Class: RuboCop::Cop::Chef::Style::UsePlatformHelpers

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

Overview

Use the platform?() and platform_family?() helpers instead of node == ‘foo’ and node == ‘bar’. These helpers are easier to read and can accept multiple platform arguments, which greatly simplifies complex platform logic.

Examples:


### incorrect
node['platform'] == 'ubuntu'
node['platform_family'] == 'debian'
node['platform'] != 'ubuntu'
node['platform_family'] != 'debian'
%w(rhel suse).include?(node['platform_family'])
node['platform'].eql?('ubuntu')

### correct
platform?('ubuntu')
!platform?('ubuntu')
platform_family?('debian')
!platform_family?('debian')
platform_family?('rhel', 'suse')

Constant Summary collapse

MSG =
"Use platform? and platform_family? helpers to check a node's platform"
RESTRICT_ON_SEND =
[:==, :!=, :eql?, :include?].freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_send(node) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rubocop/cop/chef/style/use_platform_helpers.rb', line 59

def on_send(node)
  platform_equals?(node) do |type, operator, plat|
    add_offense(node, severity: :refactor) do |corrector|
      corrected_string = (operator == :!= ? '!' : '') + "#{type.value}?('#{plat.value}')"
      corrector.replace(node, corrected_string)
    end
  end

  platform_include?(node) do |plats, type|
    add_offense(node, severity: :refactor) do |corrector|
      platforms = plats.values.map { |x| x.str_type? ? "'#{x.value}'" : x.source }
      corrected_string = "#{type.value}?(#{platforms.join(', ')})"
      corrector.replace(node, corrected_string)
    end
  end

  platform_eql?(node) do |type, plat|
    add_offense(node, severity: :refactor) do |corrector|
      corrected_string = "#{type.value}?('#{plat.value}')"
      corrector.replace(node, corrected_string)
    end
  end
end