ActiveSupport#presence method

ActiveSupport#presence method

Table of contents

No heading

No headings in the article.

We want to set the default role to guest if both params[:role] is blank. By blank I mean either these values hold nil or '' .

Old way

def role(params: {})
    params[:role].present? ? params[:role] : 'guest'
end

Using ActiveSupport#presence

def role(params: {})
    params[:role].presence || 'guest'
end

It makes our code clean. ActiveSupport#presence returns an object if it’s #present? otherwise returns nil. object.presence is equivalent to object.present? ? object : nil

Another example:

def address(params: {})
  params[:state].presence ||
    params[:city].presence ||
    params[:country].presence ||
    'US'
end

Happy coding 🤘