Skip to content

Instantly share code, notes, and snippets.

@schneems
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schneems/8868565 to your computer and use it in GitHub Desktop.
Save schneems/8868565 to your computer and use it in GitHub Desktop.
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