Skip to content

Commit

Permalink
Merge pull request #410 from chef/default_actions
Browse files Browse the repository at this point in the history
DefaultActionFromInitialize: don't insert dupe default_action
  • Loading branch information
tas50 authored Nov 18, 2019
2 parents 13d9f7e + b5d21c2 commit a933ba1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/rubocop/cop/chef/modernize/default_action_initializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,17 @@ def on_def(node)
end
end

def_node_search :default_action_method?, '(send nil? :default_action ... )'

def_node_search :intialize_method, '(def :initialize ... )'

def autocorrect(node)
lambda do |corrector|
# insert the new default_action call above the initialize method
initialize_node = intialize_method(processed_source.ast).first
corrector.insert_before(initialize_node.source_range, "default_action #{node.descendants.first.source}\n\n")
# 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 = intialize_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))
Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/chef/modernize/default_action_initializer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ def initialize(*args)
RUBY
end

it 'Deletes the intializer usage it if the DSL method already exists' do
expect_offense(<<~RUBY)
default_action :create
def initialize(*args)
super
@action = :create
^^^^^^^^^^^^^^^^^ The default action of a resource can be set with the "default_action" helper instead of using the initialize method.
end
RUBY

expect_correction(<<~RUBY)
default_action :create
def initialize(*args)
super
end
RUBY
end

it 'does not register an offense with an empty initialize method' do
expect_no_offenses(<<~RUBY)
def initialize(*args)
Expand Down

0 comments on commit a933ba1

Please sign in to comment.