2013-02-15 3 views
1

문자열에 zip 아카이브가 있지만 rubyzip gem이 파일의 입력을 원하는 것처럼 보입니다. 내가 가지고 올 것 중에 최고는 Zip::ZipFile.foreach()에 파일 이름을 전달하는 목적을위한 임시 파일을 압축 아카이브를 작성하는 것입니다, 그러나 이것은 고문 보인다 :문자열에서 zip 아카이브 압축 해제

require 'zip/zip' 
def unzip(page) 
    "".tap do |str| 
    Tempfile.open("unzip") do |tmpfile| 
     tmpfile.write(page) 
     Zip::ZipFile.foreach(tmpfile.path()) do |zip_entry| 
     zip_entry.get_input_stream {|io| str << io.read} 
     end 
    end 
    end 
end 

간단한 방법이 있나요?

참고 : Ruby Unzip String도 참조하십시오.

답변

3

Zip/Ruby Zip::Archive.open_buffer(...)를 참조하십시오

require 'zipruby' 
Zip::Archive.open_buffer(str) do |archive| 
    archive.each do |entry| 
    entry.name 
    entry.read 
    end 
end 
+0

감사합니다. http://stackoverflow.com/a/14912237/558639에있는 전체 답변보기 –

-1

루비의 StringIO이 경우에 도움이 될 것이다.

문자열/버퍼로 생각하면 메모리 내 파일처럼 취급 할 수 있습니다.

+0

StringIO에 대해 모두 알고 있습니다. 나는 Zip :: ZipFile이 StringIO 객체를 처리 할 수 ​​있다고 생각하지 않지만 잘못된 것으로 입증 되기는 어려울 것입니다. –

+0

파일 이름이 필요합니다. 스트림 같은 객체가 아니다. – sergeych

0

@ maerics 님의 답변이 zipruby gem (rubyzip gem과 혼동하지 말 것)에 대한 저를 소개했습니다. 잘 작동한다. 내 전체 코드는 다음과 같이 끝났습니다.

require 'zipruby' 

# Given a string in zip format, return a hash where 
# each key is an zip archive entry name and each 
# value is the un-zipped contents of the entry 
def unzip(zipfile) 
    {}.tap do |entries| 
    Zip::Archive.open_buffer(zipfile) do |archive| 
     archive.each do |entry| 
     entries[entry.name] = entry.read 
     end 
    end 
    end 
end 
관련 문제