class Docx::Builder::Template

Public Class Methods

new(path) click to toggle source
# File lib/docx/builder.rb, line 18
def initialize(path)
  @document = Docx::Decoder.to_xml(path)
  @sections = ["word/document.xml"]
  @document.each do |file|
    if file.name.include? "word/header"
      @sections.push(file.name)
    end
  end
end

Public Instance Methods

build_erb_template(document) click to toggle source
# File lib/docx/builder.rb, line 42
def build_erb_template(document)
  ret = document.gsub(/\{\{%/, '<%=').gsub(/%\}\}/, '%>')
  ret = ret.gsub(/\{\{/, '<%').gsub(/\}\}/, '%>')
  ret
end
clean(document) click to toggle source
# File lib/docx/builder.rb, line 37
def clean(document)
  document.force_encoding(Encoding::UTF_8) if document.respond_to?(:force_encoding)
  XmlProcessor.clean_variables(document)
end
render(data) click to toggle source
# File lib/docx/builder.rb, line 28
def render(data)
  @sections.map do |section|
    cleaned_document = clean(@document.read(section))
    erb_template = build_erb_template(cleaned_document)
    processed_document = render_erb_template(erb_template, data)
    [section, processed_document] 
  end.to_h
end
render_erb_template(document, data) click to toggle source
# File lib/docx/builder.rb, line 48
def render_erb_template(document, data)
  erb_template = ERB.new(document)
  ret = erb_template.result_with_hash(data)
  ret
end
save(path, new_document) click to toggle source

creates xml template keys in input docx (template file)

# File lib/docx/builder.rb, line 55
def save(path, new_document)
  File.open(path, 'wb') do |f|
    new_document_xml_string = Docx::Encoder.build_new_document_xml(@document, new_document)
    f.write(new_document_xml_string)
  end
  @document.close
end