Rails 7 adds Pathname#existence

Ashik Salman

Ashik Salman

December 7, 2021

This blog is part of our  Rails 7 series.

Rails 7 introduces Pathname#existence method, which returns the receiver if the given file path exists otherwise returns nil.

Before

We need to first check whether the given file path exist or not to perform any other operations on it.

1=> file_path = "config/schedule.yml"
2=> Pathname.new(file_path).read if Pathname.new(file_path).exist?

Rails 7 onwards

The Pathname#existence method acts like Object#presence for file existence.

1=> file_path = "config/schedule.yml"
2=> Pathname.new(file_path).existence&.read

Please check out this pull request for more details.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.