Skip to content

Instantly share code, notes, and snippets.

@brlafreniere
Created August 28, 2023 19:28
Show Gist options
  • Save brlafreniere/53a7a41c5dc357e74dc0566ed843649a to your computer and use it in GitHub Desktop.
Save brlafreniere/53a7a41c5dc357e74dc0566ed843649a to your computer and use it in GitHub Desktop.
class ZipExtractor
def initialize(source_path)
@unzipped = false
@source_path = source_path
end
##
# unzip the export and return the list of files in it
def extracted_file_list
unzip unless @unzipped
Dir[File.join(target_directory, "*")]
end
private
# The directory to unzip the download to
def target_directory
Rails.root.join("tmp", "product_catalog_export")
end
def unzip
FileUtils.rm_rf(target_directory) # delete old export
# unzip the latest export
Zip::File.open(@source_path) do |zip_file|
zip_file.each do |f|
f_path = File.join(target_directory, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
end
end
@unzipped = true
end
end
RSpec.describe Salesforce::XmlData::CatalogExport::ZipExtractor do
describe '#extracted_file_list' do
# subject / inputs
let(:source_zip_path) { Rails.root.join("tmp", "some_zip_file.zip") }
subject { described_class.new(source_zip_path) }
# mock objects
let(:file1) { instance_double("Zip::Entry", name: "file1.xml") }
let(:file2) { instance_double("Zip::Entry", name: "file2.xml") }
let(:zip_file) { instance_double("Zip::File") }
let(:extracted_file_list) { ['file1.xml', 'file2.xml']}
before do
# stubs
expect(FileUtils).to receive(:rm_rf)
expect(FileUtils).to receive(:mkdir_p).twice
expect(Zip::File).to receive(:open).and_yield(zip_file)
expect(zip_file).to receive(:each).and_yield(file1).and_yield(file2)
expect(zip_file).to receive(:extract).twice
expect(Dir).to receive(:[]).and_return(extracted_file_list)
end
it 'returns a list of files in a zip file' do
expect(subject.extracted_file_list).to eq(extracted_file_list)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment