Wayne Conrad
Wayne Conrad

Reputation: 108089

How to tell if File.symlink is supported

On some platforms (Windows), File.symlink is not supported by Ruby, raising a NotImplemented exception. I have some code that can work with or without symlinks, so it needs to adapt.

The only way I've come up with to discover whether or not symlinks are supported is to try to create one:

  def symlink_supported?
    Dir.mktmpdir do |dir|
      target_path = File.join(dir, 'target')
      symlink_path = File.join(dir, 'symlink')
      FileUtils.touch target_path
      begin
        FileUtils.ln_s target_path, symlink_path
        true
      rescue NotImplementedError
        false
      end
    end
  end

This is slow (lots of file system operations!) and seems clunky. The slow can be handled by memoization, but that just adds more machinery to the already clunky method.

Is there a faster or more elegant way to discover whether File.symlink is supported?

Upvotes: 2

Views: 464

Answers (1)

Stefan
Stefan

Reputation: 114218

This comes from test_fileuils.rb:

def check_have_symlink?
  File.symlink nil, nil
rescue NotImplementedError
  return false
rescue
  return true
end

The code doesn't create any symlinks (it doesn't even touch the file system). On systems supporting symlinks a TypeError is raised because of the nil parameter, otherwise (Windows) a NotImplementedError.

Upvotes: 3

Related Questions