Skip to content

Commit 1cf4749

Browse files
authored
Merge pull request rubocop#857 from r7kamura/feature/action-order-incorrect-correction
2 parents 2a96132 + 117f5b2 commit 1cf4749

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#837](https://github.com/rubocop/rubocop-rails/pull/837): Fix incorrect autocorrection of `Rails/ActionOrder` about comments. ([@r7kamura][])

lib/rubocop/cop/rails/action_order.rb

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class ActionOrder < Base
3535
extend AutoCorrector
3636
include VisibilityHelp
3737
include DefNode
38+
include RangeHelp
3839

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

@@ -80,7 +81,30 @@ def register_offense(previous, current)
8081
end
8182

8283
def correction_target(def_node)
83-
def_node.each_ancestor(:if).first || def_node
84+
range_with_comments_and_lines(def_node.each_ancestor(:if).first || def_node)
85+
end
86+
87+
def add_range(range1, range2)
88+
range1.with(
89+
begin_pos: [range1.begin_pos, range2.begin_pos].min,
90+
end_pos: [range1.end_pos, range2.end_pos].max
91+
)
92+
end
93+
94+
def range_with_comments(node)
95+
ranges = [
96+
node,
97+
*processed_source.ast_with_comments[node]
98+
].map do |element|
99+
element.location.expression
100+
end
101+
ranges.reduce do |result, range|
102+
add_range(result, range)
103+
end
104+
end
105+
106+
def range_with_comments_and_lines(node)
107+
range_by_whole_lines(range_with_comments(node), include_final_newline: true)
84108
end
85109
end
86110
end

spec/rubocop/cop/rails/action_order_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,29 @@ def index; end
187187
RUBY
188188
end
189189
end
190+
191+
context 'when action has some comments' do
192+
it 'corrects comments properly' do
193+
expect_offense(<<~RUBY)
194+
class UserController < ApplicationController
195+
# show
196+
def show; end
197+
198+
# index
199+
def index; end
200+
^^^^^^^^^^^^^^ Action `index` should appear before `show`.
201+
end
202+
RUBY
203+
204+
expect_correction(<<~RUBY)
205+
class UserController < ApplicationController
206+
# index
207+
def index; end
208+
209+
# show
210+
def show; end
211+
end
212+
RUBY
213+
end
214+
end
190215
end

0 commit comments

Comments
 (0)