Blog

Thoughts from my daily grind

Ruby on Rails: Check for existence of file and read

Posted by Ziyan Junaideen |Published: 08 December 2021 |Category: Ruby on Rails
Default Upload |

As developers, we are often required to open and read file contents. When we open a file, we first need to ensure it exists. The usual way to check for a whiles existence an open it would include an if conditional.

# RoR v6.1 and before

path = "path/to/file.ext"

if Pathname.new(path).exist?
  Pathname.new(path).read
end

# Of if it is relative to the Rails root
path = %w[path to file.ext]

if Rails.root.join(*path).exist?
  Rails.root.join(*path).read
end

While we can write the above in an online line, it is an if we could avoid.

When Ruby introduced the Safe Navigation Operator &., I wished there would have a way to use &. to read a file safely. That is what we got in this PR targeting Ruby on Rails 7.

From Ruby on Rails 7 onward, the following could be simplified as follows:

# RoR v7 onward

Pathname.new(path).existence&.read

Rails.root.join(*path).existence&.read
Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments