Pages

Wednesday 9 April 2014

RubyZip to zip the files using ROR


Ruby zip is basically used for zip the files using the ruby code. Ruby zip is very easy way to create and access the zip files. With this we can also add files to preexisting zip file.

Steps to install and use rubyzip with rails as a gem
  • RubyZip requires the following gem added to your Gemfile.
    'gem rubyzip'
  • Now run the command 'bundle install' from the console.
  • Write 'require “zip/zip” ' on the top of the file where you are writing the code for zip the files.
  • Write the code for generating the zip file as given blow
       input_filenames = ['apikey', 'print_view.rhtml', 'add.ods']
        zipfile_name = "/home/enbake/firstzip.zip"
        Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE){ |zip| input_filenames.each do     |filename|
          zip.add(filename, "/home/enbake/#{filename}")
      end
    }
  • input_filenames :- List of file's name which we want to zip.
    Files can be in any format so write the files with there extensions(eg .rhtml, .txt ).

  • zipfile_name :- Name of zip file with the full path. Give the path where you want to save the zip file.
  • Zip::ZipFile.open('zipfile_name') will return the object of the zip file and
    Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) is used to create and open the zip.
  • We have made the zip file and now we have to add files into this zip file.
  • So zip.add is used for adding the files into the zip where 'zip' is an object.
    zip.add(filename, "/home/enbake/#{filename}")

  • We will pass two parameters into zip.add.(filename, path). First parameter will be the filename and second will be the path of the filename.
    filename :- name of the file like 'print_view.rhtml'
    path :- path of the filename like '/home/dir/print_view.rhtml'.
    Note:- Pass the full path of the file which you want to zip.
  • If you want to check the number of files included in zip, 'object.size' is used.
    object = Zip::ZipFile.open('zipfile_name')

    size = object.size

    and obj.name is used to check the name of the file with path.
  • If you have created a zip file and want to add a file in that zip
    just open the zip file. You can do this by making object or write the block.
    object = Zip::ZipFile.open('zipfile_name')

    object.add(“filename”, “path_of_file”)

    zipfile_name = 'secondzip.zip'

    filename = 'zipdoc'

    path_of_file = '/home/zipdoc'

    Zip::ZipFile.open("secondzip.zip") { |zs| 
        zs.add("filename", "path_of_file")

    }

    So, this way we can add the file into the old zip file and no need to create the new zip file.
  • If the files already exists in the zip file, rubyzip does not overwrite the files and
    show errors, so for overwritting this just add this line to the code where you are creating the zip file.
    Zip.options[:continue_on_exists_proc] = true

1 comment: