Skip to content

Commit 16dfcc8

Browse files
committed
Add find-by-memoization section
1 parent 524a1ac commit 16dfcc8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

README.adoc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,28 @@ The following methods behave differently without `all`:
11311131

11321132
So, when considering removing `all` from the receiver of these methods, it is recommended to refer to the documentation to understand how the behavior changes.
11331133

1134+
=== `find_by` memoization [[find-by-memoization]]
1135+
1136+
Avoid memoizing `find_by` results with `||=`.
1137+
`find_by` may return `nil`, in which case it will not be memoized as intended.
1138+
1139+
[source,ruby]
1140+
----
1141+
# bad
1142+
def current_user
1143+
@current_user ||= User.find_by(id: session[:user_id])
1144+
end
1145+
1146+
# good
1147+
def current_user
1148+
if instance_variable_defined?(:@current_user)
1149+
@current_user
1150+
else
1151+
@current_user = User.find_by(id: session[:user_id])
1152+
end
1153+
end
1154+
----
1155+
11341156
== Migrations
11351157

11361158
=== Schema Version [[schema-version]]

0 commit comments

Comments
 (0)