Sha256: 9e4c4fa622b0cbd6a2a65ed703f54d37d24e16942e1e9747cf774320b5faa0d8

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

module Docx
    module Builder
		class Template
			def initialize(path)
				@document = Docx::Builder::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|
					Docx::Builder.logger.debug("Cleaning template variables for section #{section}")
					cleaned_document = clean(@document.read(section))
					Docx::Builder.logger.debug("Replacing template tags ('{{%' -> '<%') for section #{section}")
					erb_template = build_erb_template(cleaned_document)
					Docx::Builder.logger.debug("Rendering template for section #{section} with data")
					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)
				Docx::Builder::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)
				Docx::Builder.logger.info("Saving output file into path #{path.to_s}")
				File.open(path, 'wb') do |f|
					new_document_xml_string = Docx::Builder::Encoder.build_new_document_xml(@document, new_document)
					f.write(new_document_xml_string)
				end
				@document.close
			end
		end
    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
docx-builder-0.2.3 lib/docx/builder/template.rb