class RuboCop::Cop::Chef::Style::SimplifyPlatformMajorVersionCheck

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.

@example

#### 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

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# 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

Private Instance Methods

add_offense_to_i_if_present(node) click to toggle source

if the parent is .to_i then we want to alert on that

# File lib/rubocop/cop/chef/style/simplify_platform_major_version_check.rb, line 68
def add_offense_to_i_if_present(node)
  node = node.parent if parent_method_equals?(node, :to_i)
  add_offense(node, severity: :refactor) do |corrector|
    corrector.replace(node, "node['platform_version'].to_i")
  end
end
parent_method_equals?(node, name) click to toggle source

see if the parent is a method and if it equals the passed in name

@param [Rubocop::AST:Node] node The rubocop ast node to search @param [Symbol] name The method name

# File lib/rubocop/cop/chef/style/simplify_platform_major_version_check.rb, line 80
def parent_method_equals?(node, name)
  return false if node.parent.nil?
  return false unless node.parent.send_type?
  name == node.parent.method_name
end