Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add append-entry feature #128

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 28 additions & 27 deletions lib/docx/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -124,39 +125,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
Expand All @@ -167,8 +143,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)
Expand Down