Class: RuboCop::Cop::Chef::Style::SimplifyPlatformMajorVersionCheck

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

Overview

When checking the major version number of a platform you can take the node attribute and transform it to an integer to strip it down to just the major version number. This simple way of determining the major version number of a platform should be used instead of splitting the platform into multiple fields with ‘.’ as the delimiter.

Examples:


### incorrect
node['platform_version'].split('.').first
node['platform_version'].split('.')[0]
node['platform_version'].split('.').first.to_i
node['platform_version'].split('.')[0].to_i

### correct

# check to see if we're on RHEL 7 on a RHEL 7.6 node where node['platform_version] is 7.6.1810
if node['platform_version'].to_i == 7
  # some code
end

Constant Summary collapse

MSG =
"Use node['platform_version'].to_i instead of node['platform_version'].split('.').first or node['platform_version'].split('.')[0]"
RESTRICT_ON_SEND =
[:split].freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_send(node) ⇒ Object



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

def on_send(node)
  platform_version_check?(node) do
    if parent_method_equals?(node, :[])
      node = node.parent
      if node&.arguments.count == 1 &&
         node&.arguments&.first&.int_type? &&
         node&.arguments&.first.source == '0'
        add_offense_to_i_if_present(node)
      end
    elsif parent_method_equals?(node, :first)
      node = node.parent
      add_offense_to_i_if_present(node)
    end
  end
end