Sha256: 3af782392063518a25abe5241854f9430f3ad79b55f456692985b602218cfbef

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module Docx
  module Builder
    # Class responsible for dealing with xml nodes in-between the variables
    class XmlProcessor
      def self.clean_variables(document)
        document.gsub(/\{\{.*?\}\}/m) do |match|
          ret = match.include?('>') ? join_variable_tags(match) : match
          Docx::Builder.logger.debug("Before cleaning: #{ret}")
          ret = clean_spaces_inside_variables(ret)
          ret = insert_null_placeholder(ret)
          Docx::Builder.logger.debug("After cleaning: #{ret}")
          ret
        end
      end

      def self.join_variable_tags(match)
        before = match.gsub(/<(.*)/m, '')
        inside = match.scan(/<w:t.*?>([^>]*?)<.w:t>/m).join
        after = match.gsub(/.*>([^>]+)$/m, '\\1')
        [before, inside, after].join(' ')
      end

      def self.clean_spaces_inside_variables(match)
        ret = match.dup
        cleaner_methods = Docx::Builder::Cleaners.methods.grep(/_cleaner/)
        cleaner_methods.each do |clean_method|
          ret = Docx::Builder::Cleaners.send(clean_method, ret)
        end
        ret
      end

      def self.insert_null_placeholder(expression)
        placeholder = Docx::Builder.configuration.null_placeholder
        expression.gsub(/\{\{%\s(.+)\s%\}\}/) do |_m|
          "{{% (#{Regexp.last_match(1)} || '#{placeholder}') %}}"
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
docx-builder-0.4.0 lib/docx/builder/xml_processor.rb
docx-builder-0.3.1 lib/docx/builder/xml_processor.rb