Class: RuboCop::Cop::Chef::Modernize::DefaultActionFromInitialize

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/chef/modernize/default_action_initializer.rb

Overview

The default actions can now be specified using the ‘default_action` helper instead of using the @action variable in the resource provider initialize method. In general we recommend against writing HWRPs, but if HWRPs are necessary you should utilize as much of the resource DSL as possible.

### correct
default_action :create

Examples:


### incorrect
def initialize(*args)
  super
  @action = :create
end

### incorrect
def initialize(*args)
  super
  @default_action = :create
end

Constant Summary collapse

MSG =
'The default action of a resource can be set with the "default_action" helper instead of using the initialize method.'

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_ivasgn(node) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/chef/modernize/default_action_initializer.rb', line 55

def on_ivasgn(node)
  action_variable_assignment?(node) do
    return unless initialize_method(node.parent.parent)
    add_offense(node, severity: :refactor) do |corrector|
      # insert the new default_action call above the initialize method, but not if one already exists (this is sadly common)
      unless default_action_method?(processed_source.ast)
        initialize_node = initialize_method(processed_source.ast).first
        corrector.insert_before(initialize_node.source_range, "default_action #{node.descendants.first.source}\n\n")
      end

      # remove the variable from the initialize method
      corrector.remove(range_with_surrounding_space(range: node.loc.expression, side: :left))
    end
  end
end