5 ms·
As taylorfusak mentioned, a User#guest? method is a more natural way to handle that problem. You also could make use of ActiveModel::Conversion#to_partial_path
by awj 12y ago
As taylorfusak mentioned, a User#guest? method is a more natural way to handle that problem.
You also could make use of ActiveModel::Conversion#to_partial_path, like so:
<%= render partial: current_user %>
This implicitly calls to_partial_path on the current user object and looks up a template to render based on that result. So the user model would return "users/user" and your guest object could return "users/guest".
The problem with using nil here is that you have to remember to check it everywhere, all of your tests have to exercise both the nil and not-nil cases, and most of the "else" clauses are just going to substitute default values anyways.
In my opinion if your views know so much about your user model that substituting a "guest" object is hard, maybe it's a sign you need to pull some logic back out of your views.
- 3pt14159 12y agoI disagree. Generally you will have sections of your app that are only for logged in users, so your ACL logic in your controller handily takes care of that, while still giving you the convenience of being able to call current_user and know that you actually have a user, while still being able to say things like `if current_user` where you need it. I do like your render partial example, but in most cases you will want to be doing something like showing a like button if the user is signed in, in which case you can do: <%= render partial: current_user %> And if the current_user is nil the partial will just be skipped.