Skip to main content

Command Palette

Search for a command to run...

ActiveSupport#presence method

Updated
1 min read
ActiveSupport#presence method

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 🤘

More from this blog

T

The Developers Journey

41 posts

I am a full-stack Ruby on Rails developer with experience in TDD, PostgreSQL, Docker, Heroku, performance optimization and Flutter mobile app development.

ActiveSupport#presence method