Skip to content

Commit

Permalink
Merge pull request #857 from r7kamura/feature/action-order-incorrect-…
Browse files Browse the repository at this point in the history
…correction
  • Loading branch information
koic committed Nov 5, 2022
2 parents 2a96132 + 117f5b2 commit 1cf4749
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
@@ -0,0 +1 @@
* [#837](https://github.com/rubocop/rubocop-rails/pull/837): Fix incorrect autocorrection of `Rails/ActionOrder` about comments. ([@r7kamura][])
26 changes: 25 additions & 1 deletion lib/rubocop/cop/rails/action_order.rb
Expand Up @@ -35,6 +35,7 @@ class ActionOrder < Base
extend AutoCorrector
include VisibilityHelp
include DefNode
include RangeHelp

MSG = 'Action `%<current>s` should appear before `%<previous>s`.'

Expand Down Expand Up @@ -80,7 +81,30 @@ def register_offense(previous, current)
end

def correction_target(def_node)
def_node.each_ancestor(:if).first || def_node
range_with_comments_and_lines(def_node.each_ancestor(:if).first || def_node)
end

def add_range(range1, range2)
range1.with(
begin_pos: [range1.begin_pos, range2.begin_pos].min,
end_pos: [range1.end_pos, range2.end_pos].max
)
end

def range_with_comments(node)
ranges = [
node,
*processed_source.ast_with_comments[node]
].map do |element|
element.location.expression
end
ranges.reduce do |result, range|
add_range(result, range)
end
end

def range_with_comments_and_lines(node)
range_by_whole_lines(range_with_comments(node), include_final_newline: true)
end
end
end
Expand Down
25 changes: 25 additions & 0 deletions spec/rubocop/cop/rails/action_order_spec.rb
Expand Up @@ -187,4 +187,29 @@ def index; end
RUBY
end
end

context 'when action has some comments' do
it 'corrects comments properly' do
expect_offense(<<~RUBY)
class UserController < ApplicationController
# show
def show; end
# index
def index; end
^^^^^^^^^^^^^^ Action `index` should appear before `show`.
end
RUBY

expect_correction(<<~RUBY)
class UserController < ApplicationController
# index
def index; end
# show
def show; end
end
RUBY
end
end
end

0 comments on commit 1cf4749

Please sign in to comment.