0

I have the following Ruby script that creates a Debian package, which works fine:

#!/usr/bin/ruby

  dest = "#{File.dirname(__FILE__)}/../build"
  package = "foo"

  [
    "cd #{dest} && tar czvf data.tar.gz bin console data.sql etc filter install.rb",
    "cd #{dest} && tar czvf control.tar.gz control",
    "cd #{dest} && echo 2.0 > debian-binary",
    "cd #{dest} && ar -cr #{package}.deb debian-binary control.tar.gz data.tar.gz",
    "cd #{dest} && mv #{package}.deb ..",
    "cd #{dest} && rm data.tar.gz control.tar.gz",
  ].each do |command|
    puts command
    system(command)
  end

Is there a way in Ruby where I can leave off the "cd #{dest} &&" part of each command?

2 Answers 2

6
Dir.chdir(dest) do
  # code that shall be executed while in the dest directory
end

Dir.chdir when invoked with a block will change to the given directory, execute the block and then change back.

You can also use it without a block, in which case it will never change back.

Sign up to request clarification or add additional context in comments.

1 Comment

Sweet. Worked like a charm. Thanks!
2

Yes. Use Dir.chdir:

#!/usr/bin/ruby

  dest = "#{File.dirname(__FILE__)}/../build"
  package = "foo"

  Dir.chdir dest
  [
    "tar czvf data.tar.gz bin console data.sql etc filter install.rb",
    "tar czvf control.tar.gz control",
    "echo 2.0 > debian-binary",
    "ar -cr #{package}.deb debian-binary control.tar.gz data.tar.gz",
    "mv #{package}.deb ..",
    "rm data.tar.gz control.tar.gz",
  ].each do |command|
    puts command
    system(command)
  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.