diff --git a/lib/docx_replace.rb b/lib/docx_replace.rb index 42368bb..b8c6a26 100644 --- a/lib/docx_replace.rb +++ b/lib/docx_replace.rb @@ -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) @@ -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 @@ -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) @@ -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? diff --git a/lib/docx_replace/version.rb b/lib/docx_replace/version.rb index 992ad3c..8f1a022 100644 --- a/lib/docx_replace/version.rb +++ b/lib/docx_replace/version.rb @@ -1,3 +1,3 @@ module DocxReplace - VERSION = "1.0.3" + VERSION = "1.0.4" end