Skip to content

Commit a42dbf3

Browse files
authored
Merge pull request #358 from r7kamura/find-by-memoization
Add find-by-memoization section
2 parents 21799e2 + 16dfcc8 commit a42dbf3

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
@@ -1146,6 +1146,28 @@ The following methods behave differently without `all`:
11461146

11471147
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.
11481148

1149+
=== `find_by` memoization [[find-by-memoization]]
1150+
1151+
Avoid memoizing `find_by` results with `||=`.
1152+
`find_by` may return `nil`, in which case it will not be memoized as intended.
1153+
1154+
[source,ruby]
1155+
----
1156+
# bad
1157+
def current_user
1158+
@current_user ||= User.find_by(id: session[:user_id])
1159+
end
1160+
1161+
# good
1162+
def current_user
1163+
if instance_variable_defined?(:@current_user)
1164+
@current_user
1165+
else
1166+
@current_user = User.find_by(id: session[:user_id])
1167+
end
1168+
end
1169+
----
1170+
11491171
== Migrations
11501172

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

0 commit comments

Comments
 (0)