DRYing if @current_user.nil?

While working on one of rails applications, as I usually tend to check whether user is logged in, specially in views as follows

<% if @current_user.nil? %>
  <a href='url to login page'>
<% else %>
  <a href='some url where logged in user have access'>
<% end %>

And over some period I found this pattern repeating everywhere.

I thought of DRYing it, I wanted to have a kind of before_filter for every link that appear on the page, every link should go for login if that page or feature require user entity. and this should be handled by a common thing, similar to before_filter: login_require, on server side. I intend to achieve similar in views. A while back when I read up about html5 custom data attribute, and unobtrusive javascript etc, referring to them, I got one idea as described below, though it is not something that I am making use of custom data attribute exactly, but I found this idea useful and working. May be someone would have good suggestions here for me.

I will put any link which require user login as follows

<a href="/feature/page/" login-require >Feature</a>

And then I will have my after_load.js which will have the following event binding

jQuery('a[login-require]').bind('click', function() {
  <% if @current_user.nil? %>
    return false;
  <% else %>
    return true;
  <% end %>

13 thoughts on “DRYing if @current_user.nil?

    • Agree, I will do it. But given me these two choices, I would prefer just to have “login-require” for reasons like it is more clear and simple, straight forward… and no need to use words like data, true. And I thought ‘something=”true”‘ is same as ‘something’.

  1. Another suggestion: Unconditionally link to the restricted page, and simply redirect anonymous users to the sign-in page when they try to access a restricted page. This of course only works if you have the same link text for all users.

    • Hm, I see. I’m not sure if it’s worth the extra hassle, to be honest. Redirects are very very fast, since no HTML is loaded. Google for instance has lots of redirects every time you log in. If it’s good enough for them, it’s good enough for me. So I guess I’d just avoid doing the `if current_user` thing in the first place.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s