3

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
Jay Levitt
  • 1,680
  • 1
  • 19
  • 28

2 Answers2

4

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.

Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
  • Beat me to it. I was thinking of `args = [path, 'w', permissions].reject(&:nil?)` and `File.open(*args)` but that's needlessly complicated, a separate `extra_args` is much nicer. – mu is too short Dec 15 '11 at 18:07
  • 1
    @muistooshort: :-) I thought of using `compact`, but thought the first example should be as comprehensible as possible as is it more meant for illustration that actual use. – Marc-André Lafortune Dec 15 '11 at 18:09
1
File.open(path, 'w') do |f|
  f.puts(contents)
  f.chmod(permission) if permission
end
zed_0xff
  • 32,417
  • 7
  • 53
  • 72