Skip to content

Commit eca5594

Browse files
authored
Merge pull request rubocop#845 from koic/fix_an_incorrect_autocorrect_for_rails_action_order
[Fix rubocop#838] Fix an incorrect autocorrect for `Rails/ActionOrder`
2 parents 0d430fe + 8742dd3 commit eca5594

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#838](https://github.com/rubocop/rubocop-rails/issues/838): Fix an incorrect autocorrect for `Rails/ActionOrder` when using unconventional order of actions in conditions. ([@koic][])

lib/rubocop/cop/rails/action_order.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,17 @@ def register_offense(previous, current)
7171
current: current.method_name
7272
)
7373
add_offense(current, message: message) do |corrector|
74+
current = correction_target(current)
75+
previous = correction_target(previous)
76+
7477
corrector.replace(current, previous.source)
7578
corrector.replace(previous, current.source)
7679
end
7780
end
81+
82+
def correction_target(def_node)
83+
def_node.each_ancestor(:if).first || def_node
84+
end
7885
end
7986
end
8087
end

spec/rubocop/cop/rails/action_order_spec.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,37 @@ def show; end
115115
RUBY
116116
end
117117

118+
it 'detects unconventional order of actions in conditions' do
119+
expect_offense(<<~RUBY)
120+
class TestController < BaseController
121+
unless Rails.env.development?
122+
def edit
123+
end
124+
end
125+
126+
if Rails.env.development?
127+
def index
128+
^^^^^^^^^ Action `index` should appear before `edit`.
129+
end
130+
end
131+
end
132+
RUBY
133+
134+
expect_correction(<<~RUBY)
135+
class TestController < BaseController
136+
if Rails.env.development?
137+
def index
138+
end
139+
end
140+
141+
unless Rails.env.development?
142+
def edit
143+
end
144+
end
145+
end
146+
RUBY
147+
end
148+
118149
context 'with custom ordering' do
119150
it 'enforces custom order' do
120151
cop_config['ExpectedOrder'] = %w[show index new edit create update destroy]

0 commit comments

Comments
 (0)