Last active
August 29, 2015 13:56
-
-
Save schneems/8868565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DirThreadsafe < Dir | |
def self.chdir(target) | |
Thread.current[:pwd] = target | |
end | |
end | |
module Kernel | |
alias :_backtick_original :"`" | |
def `(value) | |
if pwd = Thread.current[:pwd] | |
value = "cd #{pwd} && #{value}" | |
end | |
_backtick_original value | |
end | |
end | |
`mkdir foo` | |
`touch foo/foo_is_not_empty` | |
`mkdir bar` | |
`touch bar/bar_is_not_empty` | |
threads = [] | |
threads << Thread.new do | |
DirThreadsafe.chdir("foo") | |
puts "foo: #{`ls`}" | |
end | |
threads << Thread.new do | |
DirThreadsafe.chdir("bar") | |
puts "bar: #{`ls`}" | |
end | |
threads.map(&:join) | |
puts "current: #{`ls`.inspect}" | |
# => foo: foo_is_not_empty | |
# => bar: bar_is_not_empty | |
# => current: "bar\nfoo\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment