def with_cwd dir
  original_dir = Dir.pwd
  begin
    Dir.chdir dir
    yield
  ensure
    Dir.chdir original_dir
  end
end

2 Comments

  1. Mike

    Duncan, you may not have realized that you can simplify this significantly as Dir.chdir already accepts a block:

    def with_cwd dir
      Dir.chdir dir do
        yield  
      end
    end

    It ensures that the current directory only changes for the context of the block. You can dispense with ‘def with_cwd’ and inline it as it is no longer necessary.

  2. duncanbeevers

    Thanks Mike,

    I should have known when I wanted to do this that Ruby would do the logical thing when handed a block. So nice!

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.