Skip to main content

Command Palette

Search for a command to run...

ActiveSupport#presence method

Updated
1 min read
ActiveSupport#presence method
P

I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.

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.