Featured Post

Create Your Own Geodatabase using Ruby on Rails and Google Maps

Geocoding with Ruby on Rails isn’t a big deal. But sometimes you have do more than simple geocoding. For real estate webpages you need information about state, county or suburb for a given address. This tutorial will show you how to build your own geodatabase without overusing google maps requests(limited...

Read More

Extract zip files with Ruby on Rails

Posted by Lars | Posted in Rails, Ruby, Tutorials | Posted on 13-04-2009

5

Some friends of mine found my first tutorial difficult to understand. So i’m going to start with smaller pieces of code and start with basic unzip functions in Ruby on Rails.

1
2
3
4
5
6
7
8
9
require 'fileutils'
require 'zip/zip'
require 'zip/zipfilesystem'

def unzip
  Zip::ZipFile.open("/path/to/file.zip").each do |single_file|
    single_file.extract(single_file.name)
  end
end

It extracts all files of file.zip into current folder. If you like to get some special file out of this zipfile you can use regular expressions to filter it out. The following example shows how to get
the xml file:

1
2
3
4
5
...
if single_file.name.downcase =~ /.xml/
  special_filename = single_file.name
end
...
delicious | digg | reddit | facebook | technorati | stumbleupon | chatintamil

Comments (5)

Hello!
I’m trying to use the example above and i’m getting an error on
require ‘zip/zip’ “no such file to load”.
What am i missing?
Is there ap lugin to install?
Thanks!

Hi Rodrigo,

you need to install the gem first. Try “gem install rubyzip”.

cu Lars

REPLY to your tweet:
http://twitter.com/LarsG/status/2046557003

I couldn’t get the gem to work for me. It acts like it’s not installed but it’s in the ‘gem list’. I noticed the gem hasn’t been updated since 2006 so I was wondering if there was a better way.

I’m using Moonshine (Rails deployment and configuration management)
http://github.com/railsmachine/moonshine
So I’m trying to install a solution using that. I may just add a package:
package ‘unzip’, :ensure => :installed
package ‘zip’, :ensure => :installed

Hi J,

I don’t have any experience with Moonshine. The gem works for me perfectly - even in actual environments with Rails 2.x.

It sounds more like a ruby / gem path problem in your environment. The behavior of - non-existing-gems-but-they-are-in-gem-list - is an error I have had some months before. I tried to upgrade the Ruby package and ended up with two installations of ruby and ruby gems.

Sorry, but I don’t know another solution for server-side zip extracting.

Kind regards,
Lars

rodrigo: try to restart your app. it should work after you did that step. i had the same problem.

Write a comment