Class: RuboCop::Cop::Chef::RedundantCode::UnnecessaryNameProperty

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

Overview

There is no need to define a property or attribute named :name in a resource as Chef Infra defines this on all resources by default.

Examples:


### incorrect
property :name, String
property :name, String, name_property: true
attribute :name, kind_of: String
attribute :name, kind_of: String, name_attribute: true
attribute :name, name_attribute: true, kind_of: String

Constant Summary collapse

MSG =
'There is no need to define a property or attribute named :name in a resource as Chef Infra defines this on all resources by default.'
RESTRICT_ON_SEND =
[:property, :attribute].freeze

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_send(node) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/chef/redundant/unnecessary_name_property.rb', line 47

def on_send(node)
  name_property?(node) do |hash_vals|
    # It's perfectly valid to redefine the name property if you give it non-default values
    # We do this in a few of our core resources where we give it a default value of "" for nameless resources
    # If there are hash vals in this attribute/property compare them with the default keys and if there's anything
    # else return so we don't alert
    unless hash_vals.empty?
      hash_keys = hash_vals.first.map { |x| x.key.value }
      return unless (hash_keys - [:kind_of, :name_attribute, :name_property]).empty?
    end

    add_offense(node, severity: :refactor) do |corrector|
      corrector.remove(node.source_range)
    end
  end
end