Skip to content

Commit 446e636

Browse files
committed
1 parent e742790 commit 446e636

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

lib/tmpdir.rb

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,20 @@
1313

1414
class Dir
1515

16-
@@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'
16+
# Class variables are inaccessible from non-main Ractor.
17+
# And instance variables too, in Ruby 3.0.
18+
19+
# System-wide temporary directory path
20+
SYSTMPDIR = (defined?(Etc.systmpdir) ? Etc.systmpdir.freeze : '/tmp')
21+
private_constant :SYSTMPDIR
1722

1823
##
1924
# Returns the operating system's temporary file path.
2025

2126
def self.tmpdir
22-
['TMPDIR', 'TMP', 'TEMP', ['system temporary path', @@systmpdir], ['/tmp']*2, ['.']*2].find do |name, dir|
27+
['TMPDIR', 'TMP', 'TEMP', ['system temporary path', SYSTMPDIR], ['/tmp']*2, ['.']*2].find do |name, dir|
2328
unless dir
24-
next if !(dir = ENV[name]) or dir.empty?
29+
next if !(dir = ENV[name] rescue next) or dir.empty?
2530
end
2631
dir = File.expand_path(dir)
2732
stat = File.stat(dir) rescue next
@@ -118,16 +123,17 @@ def tmpdir
118123
UNUSABLE_CHARS = "^,-.0-9A-Z_a-z~"
119124

120125
# Dedicated random number generator
121-
RANDOM = Random.new
126+
RANDOM = Object.new
122127
class << RANDOM # :nodoc:
123128
# Maximum random number
124129
MAX = 36**6 # < 0x100000000
125130

126131
# Returns new random string upto 6 bytes
127132
def next
128-
rand(MAX).to_s(36)
133+
(::Random.urandom(4).unpack1("L")%MAX).to_s(36)
129134
end
130135
end
136+
RANDOM.freeze
131137
private_constant :RANDOM
132138

133139
# Generates and yields random names to create a temporary name

test/test_tmpdir.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,4 +115,20 @@ def assert_mktmpdir_traversal
115115
end
116116
end
117117
end
118+
119+
def test_ractor
120+
assert_ractor(<<~'end;', require: "tmpdir")
121+
r = Ractor.new do
122+
Dir.mktmpdir() do |d|
123+
Ractor.yield d
124+
Ractor.receive
125+
end
126+
end
127+
dir = r.take
128+
assert_file.directory? dir
129+
r.send true
130+
r.take
131+
assert_file.not_exist? dir
132+
end;
133+
end
118134
end

0 commit comments

Comments
 (0)