Class: RuboCop::Cop::Chef::Modernize::ProvidesFromInitialize

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

Overview

Provides should be set using the ‘provides` resource DSL method instead of instead of setting @provides in the initialize method.

Examples:


### incorrect
def initialize(*args)
  super
  @provides = :foo
end

### correct
provides :foo

Constant Summary collapse

MSG =
'Provides should be set using the `provides` resource DSL method instead of instead of setting @provides in the initialize method.'

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_ivasgn(node) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/chef/modernize/provides_initializer.rb', line 45

def on_ivasgn(node)
  provides_assignment?(node) do
    return unless initialize_method(node.parent.parent).any?
    add_offense(node, severity: :refactor) do |corrector|
      # insert the new provides call above the initialize method, but not if one already exists (this is sadly common)
      unless provides_method?(processed_source.ast)
        initialize_node = initialize_method(processed_source.ast).first
        corrector.insert_before(initialize_node.source_range, "provides #{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