Skip to content
Open
Show file tree
Hide file tree
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
42 changes: 30 additions & 12 deletions lib/docx_replace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

module DocxReplace
class Doc
attr_reader :document_content
DOCUMENT_FILE_PATH = 'word/document.xml'

attr_accessor :document_contents

def initialize(path, temp_dir=nil)
@zip_file = Zip::File.new(path)
Expand All @@ -15,20 +17,28 @@ def initialize(path, temp_dir=nil)
end

def replace(pattern, replacement, multiple_occurrences=false)
replace = replacement.to_s
replace = replacement.to_s.encode(xml: :text)
if multiple_occurrences
@document_content.force_encoding("UTF-8").gsub!(pattern, replace)
@document_contents.keys.each do |name|
@document_contents[name].force_encoding("UTF-8").gsub!(pattern, replace)
end
else
@document_content.force_encoding("UTF-8").sub!(pattern, replace)
@document_contents.keys.each do |name|
@document_contents[name].force_encoding("UTF-8").sub!(pattern, replace)
end
end
end

def matches(pattern)
@document_content.scan(pattern).map{|match| match.first}
def matches(pattern, unique = false)
if unique
@document_contents[DOCUMENT_FILE_PATH].scan(pattern).map{|match| match.first}
else
@document_contents[DOCUMENT_FILE_PATH].scan(pattern).flatten.inject(Hash.new(0)) { |hash, key| hash[key] += 1; hash }
end
end

def unique_matches(pattern)
matches(pattern)
matches(pattern, true)
end

alias_method :uniq_matches, :unique_matches
Expand All @@ -39,10 +49,16 @@ def commit(new_path=nil)
end

private
DOCUMENT_FILE_PATH = 'word/document.xml'

def read_docx_file
@document_content = @zip_file.read(DOCUMENT_FILE_PATH)
@document_contents = {}

@zip_file.entries.each do |entry|
if entry.name.match? /^word\/(document|header[0-9]+|footer[0-9]+).xml/
@document_contents[entry.name] = @zip_file.read(entry.name)
end
end

end

def write_back_to_file(new_path=nil)
Expand All @@ -53,14 +69,16 @@ def write_back_to_file(new_path=nil)
end
Zip::OutputStream.open(temp_file.path) do |zos|
@zip_file.entries.each do |e|
unless e.name == DOCUMENT_FILE_PATH
unless @document_contents.keys.include? e.name
zos.put_next_entry(e.name)
zos.print e.get_input_stream.read
end
end

zos.put_next_entry(DOCUMENT_FILE_PATH)
zos.print @document_content
@document_contents.each do |name, content|
zos.put_next_entry(name)
zos.print content
end
end

if new_path.nil?
Expand Down
2 changes: 1 addition & 1 deletion lib/docx_replace/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module DocxReplace
VERSION = "1.0.3"
VERSION = "1.0.4"
end