Checking Presence in Rails
Instead of using .empty?
or .blank?
, Rails provides us with a great method called .presence
. This method:
Returns the receiver if it’s present otherwise returns nil. object.presence is equivalent to.
This is great to use to clean up ternaries. Let’s say you had something like this:
foo = bar.name.empty? ? "No name" || bar.name
Using .presence
we can rewrite this:
foo = bar.name.presence || "No name"
While it’s only a few characters shorter, it reads so much better.
The Rails docs has a good example:
state = params[:state] if params[:state].present?
country = params[:country] if params[:country].present?
region = state || country || 'US'
Becomes:
region = params[:state].presence || params[:country].presence || 'US'
So give it a go! See where you can save a few characters and improve readability in your code base.
Upgrade Your Conditionals
Another great example is using it in an assignment conditional. I use the following for building this site:
<% if tldr = current_page.data.tldr.presence %>
<div class="article-tldr">
<h4 title="Too Long, Didn't Read">tl;dr</h4>
<%= Tilt::RedcarpetTemplate.new { tldr }.render %>
</div>
<% end %>
If current_page.data.tldr.presence
returns nil
the content is not rendered. If it has content it will be assigned to tldr
and we can use that later inside the block.