Skip to content

Commit 501e5d3

Browse files
committed
[Fix #1513] Tweak autocorrection code for Rails/FindByOrAssignmentMemoization
Follow-up to rubocop/rails-style-guide#368. Closes #1513.
1 parent f178f30 commit 501e5d3

File tree

2 files changed

+9
-15
lines changed

2 files changed

+9
-15
lines changed

lib/rubocop/cop/rails/find_by_or_assignment_memoization.rb

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,9 @@ module Rails
2020
#
2121
# # good
2222
# def current_user
23-
# if instance_variable_defined?(:@current_user)
24-
# @current_user
25-
# else
26-
# @current_user = User.find_by(id: session[:user_id])
27-
# end
23+
# return @current_user if defined?(@current_user)
24+
#
25+
# @current_user = User.find_by(id: session[:user_id])
2826
# end
2927
class FindByOrAssignmentMemoization < Base
3028
extend AutoCorrector
@@ -49,11 +47,9 @@ def on_send(node)
4947
corrector.replace(
5048
assignment_node,
5149
<<~RUBY.rstrip
52-
if instance_variable_defined?(:#{varible_name})
53-
#{varible_name}
54-
else
55-
#{varible_name} = #{find_by.source}
56-
end
50+
return #{varible_name} if defined?(#{varible_name})
51+
52+
#{varible_name} = #{find_by.source}
5753
RUBY
5854
)
5955
end

spec/rubocop/cop/rails/find_by_or_assignment_memoization_spec.rb

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@
99
RUBY
1010

1111
expect_correction(<<~RUBY)
12-
if instance_variable_defined?(:@current_user)
13-
@current_user
14-
else
15-
@current_user = User.find_by(id: session[:user_id])
16-
end
12+
return @current_user if defined?(@current_user)
13+
14+
@current_user = User.find_by(id: session[:user_id])
1715
RUBY
1816
end
1917
end

0 commit comments

Comments
 (0)