DEV Community

Edward Loveall
Edward Loveall

Posted on


The Rails presence Method

Note: This article was originally written at

Rails has a convenient method that I discovered the other day: presence. All it does is return itself if present?. It's a pretty simple method:

def presence
  self if present?
Enter fullscreen mode Exit fullscreen mode

The documentation has a great example that simplifies this:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'
Enter fullscreen mode Exit fullscreen mode

to this:

region = params[:state].presence || params[:country].presence || 'US'
Enter fullscreen mode Exit fullscreen mode

Here's another use case. Imagine your app has a page where you can search for users. There's a show.html.erb template, and two partials: user.html.erb and no_results.html.erb.

Your controller will search for users and assign them to an instance variable. If no users were found, we'd rather show the no_results partial instead of a blank page:

<% if @users.present? %>
  <%= render @users %>
<% else %>
  <% render 'no_results' %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

With presence we can make this code shorter but still readable.

<%= render @users.presence || 'no_results' %>
Enter fullscreen mode Exit fullscreen mode

Most of the time present? is probably what you're looking for, but sometimes presence really cleans up your code. Keep it in mind.

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.