class Docxgen::Templates::Parser

Constants

VARIABLE_REGEX

Public Class Methods

find_variables(tr) click to toggle source
# File lib/docxgen/templates/parser.rb, line 26
def self.find_variables(tr)
  tr.to_s.scan(VARIABLE_REGEX).map do |match|
    src, path, *_ = match

    {
      src: src,
      path: path.split(".").reject(&:empty?).map do |p|
        Integer(p) rescue next p.to_sym

        p.to_i
      end
    }
  end
end
tr_substitute!(tr, data, remove_missing: true) click to toggle source
# File lib/docxgen/templates/parser.rb, line 8
def self.tr_substitute!(tr, data, remove_missing: true)
  found_variables = self.find_variables(tr)

  errors = []

  found_variables.each do |var|
    value = data.dig(*var[:path])

    errors.push("No value provided for variable: #{var[:src]}") if value.nil?

    next if value.nil? && !remove_missing # Don't replace variables with empty string if remove_missing is false

    tr.substitute(var[:src], value || "")
  end

  [tr, errors]
end