grigoryvp
grigoryvp

Reputation: 42463

Is it possible to use Ruby temp directory engine with non-english file names on Windows?

I am creating a temporary directory in Ruby using 'tmpdir', and adding a file in the temporary directory that has a non-English file name:

#!/usr/bin/env ruby -KU
# coding:utf-8

require 'tmpdir'
Dir.mktmpdir { |dir| File.open( "#{dir}/файл.txt", "w" ) {} }

The program fails on cleanup, attempting to delete "????.txt". I can see the file is being created with the appropriate name.

I am running Ruby 1.9 on Windows. Is there some way to fix this, or is Ruby 1.9 not intended to be used with non-English characters on Windows?

Upvotes: 3

Views: 306

Answers (2)

grigoryvp
grigoryvp

Reputation: 42463

This is a bug introduced more than 2 years ago by typo. Will be fixed in Ruby 2.0 :( http://goo.gl/SsAA8

For ruby version < 2.0 this hack defined after require 'tmpdir' will fix a problem:

if RUBY_VERSION < '2.0' then
  ##  Fix bug |http://goo.gl/SsAA8|.
  class FileUtils::Entry_
    def entries
      opts = {}
      opts[:encoding] = "UTF-8" if /mswin|mingw/ =~ RUBY_PLATFORM
      Dir.entries(path(), opts)\
          .reject {|n| n == '.' or n == '..' }\
          .map {|n| FileUtils::Entry_.new(prefix(), join(rel(), n.untaint)) }
    end
  end
end

Upvotes: 1

robustus
robustus

Reputation: 3706

Well i'm pretty sure this is a bug. The method tmpdir is using the cleanup after itself can't recognize the utf-8 filename (probably a ruby/windows problem or ruby-specific)

The following would be a workaround:

#!/usr/bin/env ruby -KU
# coding:utf-8

require 'tmpdir'
Dir.mktmpdir do |dir| 
  File.open( "#{dir}/файл.txt", "w" ) {} 
  FileUtils.remove_entry_secure "#{dir}/файл.txt"
end

This removes the 'odd' file before removing the folder. A Little bit of a hack, but it should work (tested it).

Upvotes: 1

Related Questions