Class: Consolidate::Docx::Merge

Inherits:
Object
  • Object
show all
Defined in:
lib/consolidate/docx/merge.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, verbose: false, &block) ⇒ Merge

Returns a new instance of Merge.



14
15
16
17
18
19
20
# File 'lib/consolidate/docx/merge.rb', line 14

def initialize(path, verbose: false, &block)
  @verbose = verbose
  @output = {}
  @zip = Zip::File.open(path)
  @documents = load_documents
  block&.call self
end

Class Method Details

.open(path, verbose: false, &block) ⇒ Object



9
10
11
12
# File 'lib/consolidate/docx/merge.rb', line 9

def self.open(path, verbose: false, &block)
  new(path, verbose: verbose, &block)
  path
end

Instance Method Details

#data(mapping = {}) ⇒ Object

Substitute the data from the merge fields with the values provided



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/consolidate/docx/merge.rb', line 43

def data mapping = {}
  mapping = mapping.transform_keys(&:to_s)

  if verbose
    puts "...substitutions..."
    mapping.each do |key, value|
      puts "      #{key} => #{value}"
    end
  end

  @documents.each do |name, document|
    output_document = substitute document.dup, mapping: mapping, document_name: name

    @output[name] = output_document.serialize save_with: 0
  end
end

#document_namesObject

List the documents stored within this docx



38
39
40
# File 'lib/consolidate/docx/merge.rb', line 38

def document_names
  @zip.entries.collect { |entry| entry.name }
end

#examineObject

Helper method to display the contents of the document and the merge fields from the CLI



23
24
25
26
27
28
# File 'lib/consolidate/docx/merge.rb', line 23

def examine
  documents = document_names.join(", ")
  fields = field_names.join(", ")
  puts "Documents: #{documents}"
  puts "Merge fields: #{fields}"
end

#field_namesObject

Read all documents within the docx and extract any merge fields



31
32
33
34
35
# File 'lib/consolidate/docx/merge.rb', line 31

def field_names
  tag_nodes.collect do |tag_node|
    field_names_from tag_node
  end.flatten.compact.uniq
end

#write_to(path) ⇒ Object

Write the new document to the given path



61
62
63
64
65
66
67
68
69
70
# File 'lib/consolidate/docx/merge.rb', line 61

def write_to path
  puts "...writing to #{path}" if verbose
  Zip::File.open(path, Zip::File::CREATE) do |out|
    zip.each do |entry|
      out.get_output_stream(entry.name) do |o|
        o.write(output[entry.name] || zip.read(entry.name))
      end
    end
  end
end