Skip to content

Commit d0d6fb6

Browse files
committed
Added streaming result instead of saving to a path
1 parent bef239d commit d0d6fb6

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

lib/docx/document.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,27 @@ def save(path)
121121
zip.close
122122
end
123123

124+
# Output entire document as a StringIO object
125+
def stream
126+
update
127+
stream = Zip::OutputStream.write_buffer do |out|
128+
zip.each do |entry|
129+
next unless entry.file?
130+
131+
out.put_next_entry(entry.name)
132+
133+
if @replace[entry.name]
134+
out.write(@replace[entry.name])
135+
else
136+
out.write(zip.read(entry.name))
137+
end
138+
end
139+
end
140+
141+
stream.rewind
142+
stream
143+
end
144+
124145
alias text to_s
125146

126147
def replace_entry(entry_path, file_contents)

spec/docx/document_spec.rb

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
end
4949
end
5050

51-
shared_examples_for 'saving' do
51+
shared_examples_for 'saving to file' do
5252
it 'should save to a normal file path' do
5353
@new_doc_path = @fixtures_path + '/new_save.docx'
5454
@doc.save(@new_doc_path)
@@ -359,7 +359,7 @@
359359
@doc = Docx::Document.open(@fixtures_path + '/saving.docx')
360360
end
361361

362-
it_behaves_like 'saving'
362+
it_behaves_like 'saving to file'
363363
end
364364

365365
context 'from a stream' do
@@ -368,7 +368,7 @@
368368
@doc = Docx::Document.open_buffer(stream)
369369
end
370370

371-
it_behaves_like 'saving'
371+
it_behaves_like 'saving to file'
372372
end
373373

374374
context 'wps modified docx file' do
@@ -382,6 +382,13 @@
382382
end
383383
end
384384

385+
describe 'streaming' do
386+
it 'should return a StringIO to send over HTTP' do
387+
doc = Docx::Document.open(@fixtures_path + '/basic.docx')
388+
expect(doc.stream).to be_a(StringIO)
389+
end
390+
end
391+
385392
describe 'outputting html' do
386393
before do
387394
@doc = Docx::Document.open(@fixtures_path + '/formatting.docx')

0 commit comments

Comments
 (0)