Class: RuboCop::Cop::Chef::Correctness::PlatformVersionStringComparison

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/chef/correctness/platform_version_string_comparison.rb

Overview

Ohai reports version attributes as strings, so comparing one with <, >, <=, or >= compares them character by character rather than as versions. That gives the wrong answer whenever the version numbers have different digit counts:

'7.9' >= '10'   # => true, because '7' sorts after '1'
'9' > '10'      # => true

Compare the major version as an integer with node['platform_version'].to_i, or compare full versions with Gem::Version.

Examples:


# bad
node['platform_version'] >= '10'
node['platform_version'] < '7.4'

# good
node['platform_version'].to_i >= 10
Gem::Version.new(node['platform_version']) >= Gem::Version.new('7.4')

# good - equality is a plain string match, which is fine
node['platform_version'] == '10'

Constant Summary collapse

MSG =
'Ohai version attributes are strings, so comparing them with an ordering operator compares them character by character. Use .to_i for a major version comparison, or Gem::Version to compare full versions.'
RESTRICT_ON_SEND =
%i(< > <= >=).freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_send(node) ⇒ Object



57
58
59
60
61
# File 'lib/rubocop/cop/chef/correctness/platform_version_string_comparison.rb', line 57

def on_send(node)
  version_attribute_comparison?(node) do
    add_offense(node, severity: :refactor)
  end
end