From 21f68d19992d69a2422e7278d2868a0377485c9a Mon Sep 17 00:00:00 2001 From: Justin Date: Tue, 28 Jun 2022 12:00:52 +0800 Subject: [PATCH 1/2] Add append entry feature --- lib/docx/document.rb | 54 ++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/docx/document.rb b/lib/docx/document.rb index fb52477..9da0708 100755 --- a/lib/docx/document.rb +++ b/lib/docx/document.rb @@ -124,39 +124,14 @@ def to_html # save(filepath) => void def save(path) update - Zip::OutputStream.open(path) do |out| - zip.each do |entry| - next unless entry.file? - - out.put_next_entry(entry.name) - - if @replace[entry.name] - out.write(@replace[entry.name]) - else - out.write(zip.read(entry.name)) - end - end - end + Zip::OutputStream.open(path) { |out| write_to_stream(out) } zip.close end # Output entire document as a StringIO object def stream update - stream = Zip::OutputStream.write_buffer do |out| - zip.each do |entry| - next unless entry.file? - - out.put_next_entry(entry.name) - - if @replace[entry.name] - out.write(@replace[entry.name]) - else - out.write(zip.read(entry.name)) - end - end - end - + stream = Zip::OutputStream.write_buffer { |out| write_to_stream(out) } stream.rewind stream end @@ -167,8 +142,33 @@ def replace_entry(entry_path, file_contents) @replace[entry_path] = file_contents end + def append_entry(entry_path, file_contents) + @append[entry_path] = file_contents + end + private + def write_to_stream(out) + zip.each do |entry| + next unless entry.file? + + out.put_next_entry(entry.name) + + if @replace[entry.name] + out.write(@replace[entry.name]) + else + out.write(zip.read(entry.name)) + end + end + + if @append.any? + @append.each do |entry_name, content| + out.put_next_entry(entry_name) + out.write(content) + end + end + end + def load_styles @styles_xml = @zip.read('word/styles.xml') @styles = Nokogiri::XML(@styles_xml) From 86a8c5624313fe6c18d24e6bfddb3633311d954e Mon Sep 17 00:00:00 2001 From: Justin Date: Tue, 28 Jun 2022 13:53:33 +0800 Subject: [PATCH 2/2] append initialize --- lib/docx/document.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/docx/document.rb b/lib/docx/document.rb index 9da0708..6608330 100755 --- a/lib/docx/document.rb +++ b/lib/docx/document.rb @@ -22,6 +22,7 @@ class Document def initialize(path_or_io, options = {}) @replace = {} + @append = {} # if path-or_io is string && does not contain a null byte if (path_or_io.instance_of?(String) && !/\u0000/.match?(path_or_io))