# frozen_string_literal: true require_relative "builder/version" require_relative "decoder" require_relative "encoder" require_relative "xml_processor" require 'rubygems' require 'zip' require 'nokogiri' module Docx module Builder class Error < StandardError; end class Template 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 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 def clean(document) document.force_encoding(Encoding::UTF_8) if document.respond_to?(:force_encoding) XmlProcessor.clean_variables(document) end def build_erb_template(document) ret = document.gsub(/\{\{%/, '<%=').gsub(/%\}\}/, '%>') ret = ret.gsub(/\{\{/, '<%').gsub(/\}\}/, '%>') ret end def render_erb_template(document, data) erb_template = ERB.new(document) ret = erb_template.result_with_hash(data) ret end # creates xml template keys in input docx (template file) 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 end end end