class DocxReplace::Doc

Constants

DOCUMENT_FILE_PATH

Attributes

document_content[R]

Public Class Methods

new(path, temp_dir=nil) click to toggle source
# File lib/docx_replace.rb, line 11
def initialize(path, temp_dir=nil)
  @zip_file = Zip::File.new(path)
  @temp_dir = temp_dir
  read_docx_file
end

Public Instance Methods

commit(new_path=nil) click to toggle source
# File lib/docx_replace.rb, line 37
def commit(new_path=nil)
  write_back_to_file(new_path)
end
matches(pattern) click to toggle source
# File lib/docx_replace.rb, line 26
def matches(pattern)
  @document_content.scan(pattern).map{|match| match.first}
end
replace(pattern, replacement, multiple_occurrences=false) click to toggle source
# File lib/docx_replace.rb, line 17
def replace(pattern, replacement, multiple_occurrences=false)
  replace = replacement.to_s.encode(xml: :text)
  if multiple_occurrences
    @document_content.force_encoding("UTF-8").gsub!(pattern, replace)
  else
    @document_content.force_encoding("UTF-8").sub!(pattern, replace)
  end
end
uniq_matches(pattern)
Alias for: unique_matches
unique_matches(pattern) click to toggle source
# File lib/docx_replace.rb, line 30
def unique_matches(pattern)
  matches(pattern)
end
Also aliased as: uniq_matches

Private Instance Methods

read_docx_file() click to toggle source
# File lib/docx_replace.rb, line 44
def read_docx_file
  @document_content = @zip_file.read(DOCUMENT_FILE_PATH)
end
write_back_to_file(new_path=nil) click to toggle source
# File lib/docx_replace.rb, line 48
def write_back_to_file(new_path=nil)
  if @temp_dir.nil?
    temp_file = Tempfile.new('docxedit-')
  else
    temp_file = Tempfile.new('docxedit-', @temp_dir)
  end
  Zip::OutputStream.open(temp_file.path) do |zos|
    @zip_file.entries.each do |e|
      unless e.name == DOCUMENT_FILE_PATH
        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
  end

  if new_path.nil?
    path = @zip_file.name
    FileUtils.rm(path)
  else
    path = new_path
  end
  FileUtils.mv(temp_file.path, path)
  @zip_file = Zip::File.new(path, true)
end