Reputation: 665
How can I zip an XML file in Ruby?
For example i have a method:
def write_data(data)
File.open(@filepath,"w") do |f|
f.write(%[<?xml version="1.0" encoding="UTF-8"?>\n])
f.write(%[<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n])
f.write(data)
f.write(%[</urlset>])
f.close
end
end
The file it creates is an XML file. I want to zip it so that it has a format test.xml.gz
.
Upvotes: 3
Views: 1358
Reputation: 3472
File.open(@filepath, 'w') do |f|
gz = Zlib::GzipWriter.new(f)
gz.write(%[<?xml version="1.0" encoding="UTF-8"?>\n])
gz.write(%[<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n])
gz.write(data)
gz.write(%[</urlset>])
gz.close
end
see
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/zlib/rdoc/Zlib/GzipWriter.html
Upvotes: 2
Reputation: 72675
You can either compress the generated file by executing a shell command %x(gzip #{@filepath})
, or compress data by zlib library and then write to the file.
Upvotes: 1