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:
def ensure_file(path, contents, permissions=nil)
# Build you array:
extra_args = []
extra_args << permissions if permissions
# Use it:
File.open(path, 'w', *extra_args) do |f|
f.puts(contents)
end
end
In this case, you are already getting permissions as a parameter, so you can simplify this (and make it even more general) by allowing any number of optional arguments and passing them:
def ensure_file(path, contents, *extra_args)
File.open(path, 'w', *extra_args) do |f|
f.puts(contents)
end
end
The only difference is that if too many arguments are passed, the ArgumentError will be raised when calling File.open instead of your ensure_file.
File.open(path, 'w') do |f|
f.puts(contents)
f.chmod(permission) if permission
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With