Supporting guest users in a Rails app

Many apps place content behind an account wall. Bringing that wall down and allowing guest users can make content more discoverable and open it up to search engines.

You might often reference the logged in user, to get their first name, for instance. Most authentication gems, like Devise, provide a current_user helper that contains whoever is logged in.

If no one is logged in, however, current_user will trigger an error if you try to a call a method on it. For instance, current_user.first_name would result in an error if no one is logged in.

To get around this, create a guest user class called GuestUser, and give it properties that a real user would have.

Add any other properties that you use with current_user.

Finally, adjust the current_user method to use GuestUser:

If you are using Devise, use this code instead of the previous block to avoid a potential conflict:

Now, you never have to check current_user for nil because it will always equal an actual user or the guest user.

Explore this concept: brings Rails job offers to you. Free for candidates. Salaries from $75,000 to $250,000. Sign up now!

Leave a Reply