My second Ruby script
I recently got my Black Nintendo DS Lite (which I haven't blogged about yet, but I should do it soon with pictures). Anyway I renamed a bunch of zip files I had to the name I want, but the patcher software used the name of the file in the zip instead. So rather than giving in to doing manual work or using Perl (as usual) I decided to take the Ruby route again. This time it was a bit harder. I found that I could just require the class name that I wanted just like Java's import statement. At least I think so, I was able to require "FileUtils" so I can get the mkdir, chdir functions. What took me a while to find (and by the time I found it, it was too late) was a zip file library to unzip a file easily. The gem query --remote zip and gem query --remote unzip gave me lots of results and mostly not what I wanted. Of course RTFMing more closely I needed an extra parameter gem query --remote --name-matches 'zip' and that gave me rubyzip as the first match. Oh well too late now. So without rubyzip, this is the script I ended up with. Note the system call.
require "find"
require "FileUtils"
require "ftools"
Find.find(".") do |file_name|
if file_name =~ /\.\/(.*)\.zip$/
basename = $1;
print basename + "\n";
FileUtils.mkdir('x')
FileUtils.chdir('x')
system ("unzip \".#{file_name}\"")
Dir.foreach(".") {
|extfile|
if extfile =~ /\.rmx$/
FileUtils.mv(extfile, "../#{basename}.rmx")
end
}
FileUtils.chdir('..')
FileUtils.rm_rf('x')
end
end

4 comments:
The updated version with rubyzip
require "find"
require "FileUtils"
require "ftools"
require "zip/zip"
require "zip/zipfilesystem"
Find.find(".") do |file_name|
if file_name =~ /\.\/(.*)\.zip$/
basename = $1;
Zip::ZipFile.open(file_name) {
|zipFile|
zipFile.dir.foreach(".") {
|fileInZip|
if fileInZip =~ /\.egs$/
zipFile.extract(fileInZip, basename + ".egs");
end
}
}
FileUtils.rm(file_name);
end
end
Man that looks ugly. It looks like object oriented perl. The "|var|" construct seems a bit ugly looking. And it seems I can construct individual objects in a number of ways rather than just "new"
The require construct looks a bit ugly too. I don't see how they relate to my main body of code too well. Plus it doesn't have a solidly defined namespace structure like Java has.
This snippet should do the job as well, it's mostly a beautified version of your original.
It mostly looks like perl because you are using it like perl ;)
and requires define their own 'namespace', in ruby a file is not equivalent with a class.
yup you're right I am writing it like Perl at that time because I have a Perl background.
Well as time goes by I'll learn more of the API when I do Ruby.
I intermix choosing between Python and Ruby when my natural inclination is Perl/Java just to give myself a mental challenge.
Post a Comment