There must be a DRY way to do this without two separate calls to File.open, and without peeking at what File.open‘s default value for permissions is. Right?
def ensure_file(path, contents, permissions=nil)
if permissions.nil?
File.open(path, 'w') do |f|
f.puts(contents)
end
else
File.open(path, 'w', permissions) do |f|
f.puts(contents)
end
end
end
Using a splat (i.e.
*some_array) will work in the general case:In this case, you are already getting
permissionsas a parameter, so you can simplify this (and make it even more general) by allowing any number of optional arguments and passing them:The only difference is that if too many arguments are passed, the
ArgumentErrorwill be raised when callingFile.openinstead of yourensure_file.