Simplifying code using Rails presence Method

Rails has a useful method called presence that allows you to use the value of an object, otherwise it returns nil.

It is very simple. Below is the implemenation.

  def presence
    self if present?
  end

We can use it to refactor the following code

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'

to this

region = params[:state].presence || params[:country].presence || 'US' 

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Detect iframe click events with pointer-events

Detect iframe click events with pointer-events