Class: RuboCop::Cop::Chef::ChefCorrectness::NamePropertyIsRequired

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/chef/correctness/name_property_and_required.rb

Overview

When using properties in a custom resource you shouldn’t set a property to be both required and a name_property. Name properties are a way to optionally override the name given to the resource block in cookbook code. In your resource code you use the name_property and if the user doesn’t pass in anything to that property its value will be populated with resource block’s name. This allows users to provide more friendly resource names for logging that give additional context on the change being made.

How about a nice example! Here we have a resource called ntp_config that has a name_property of config_file. All throughout the code of this resource we’d use new_resource.config_file when referencing the path to the config.

We can use a friendly name for the block and specific a value to config_file ntp_config ‘Configure the main config file’ do

config_file '/etc/ntp/ntp.conf'
action :create

end

We can also just set the config path as the resource block and Chef will make sure to pass this in as new_resource.config_file as well. ntp_config ‘/etc/ntp/ntp.conf’ do

action :create

end

The core tenant of the name property feature is that these properties are optional and making them required effectively turns off the functionality provided by name properties. If the goal is to always require the user to pass the config_file property then it should just be made a required property and not a name_property.

Examples:


# bad
property :config_file, String, required: true, name_property: true
attribute :config_file, String, required: true, name_attribute: true

# good
property :config_file, String, required: true

Constant Summary collapse

MSG =
'Resource properties marked as name properties should not also be required properties'.freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



64
65
66
67
68
# File 'lib/rubocop/cop/chef/correctness/name_property_and_required.rb', line 64

def on_send(node)
  if required_property?(node) && property_is_name_property?(node)
    add_offense(node, location: :expression, message: MSG, severity: :refactor)
  end
end