Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass optional argument from parent to child in Ruby

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
like image 843
Jay Levitt Avatar asked Jan 25 '26 07:01

Jay Levitt


2 Answers

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.

like image 114
Marc-André Lafortune Avatar answered Jan 28 '26 01:01

Marc-André Lafortune


File.open(path, 'w') do |f|
  f.puts(contents)
  f.chmod(permission) if permission
end
like image 41
zed_0xff Avatar answered Jan 27 '26 23:01

zed_0xff