Forked from abachman/conditional_chaining_with_tap.rb
Created
February 2, 2022 14:29
-
-
Save yassinagx/7962edd38dbf13cbb816f5f838f21c26 to your computer and use it in GitHub Desktop.
Conditional query chaining in Rails 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I want a list of 6 non-administrators who are not the | |
# current user only if someone is logged in. Otherwise, | |
# don't check current_user's id. | |
# instead of this: | |
if user_signed_in? | |
@other_users = User.non_admin.limit(6).where("name IS NOT NULL") | |
else | |
@other_users = User.non_admin.limit(6).where(['id != ?', @user.id]).where("name IS NOT NULL") | |
end | |
# I can write: | |
@other_users = User.non_admin.limit(6).tap {|query| | |
query.where(['id != ?', @user.id]) if user_signed_in? | |
}.where("name IS NOT NULL") | |
# The "if user_signed_in?" inside the tap block means I am | |
# conditionally modifying the query midstream. The same | |
# object is passed out the other side of the tap statement | |
# whether or not the additional .where is ever evaluated. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment