Class: DocxTools::MailMerge

Inherits:
Object
  • Object
show all
Defined in:
lib/docx_tools/mail_merge.rb

Constant Summary collapse

REGEXP =
/ MERGEFIELD "?([^ ]+?)"? (| \\\* MERGEFORMAT )/i.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_object) ⇒ MailMerge

Returns a new instance of MailMerge.



7
8
9
10
11
# File 'lib/docx_tools/mail_merge.rb', line 7

def initialize(file_object)
  self.document  = Document.new(file_object)
  self.part_list = PartList.new(document, %w[document.main header footer settings])
  process_merge_fields
end

Instance Attribute Details

#documentObject

Returns the value of attribute document.



5
6
7
# File 'lib/docx_tools/mail_merge.rb', line 5

def document
  @document
end

#part_listObject

Returns the value of attribute part_list.



5
6
7
# File 'lib/docx_tools/mail_merge.rb', line 5

def part_list
  @part_list
end

Instance Method Details

#fieldsObject



13
14
15
16
17
18
19
20
21
# File 'lib/docx_tools/mail_merge.rb', line 13

def fields
  fields = Set.new
  part_list.each_part do |part|
    part.xpath('.//w:MergeField').each do |mf|
      fields.add(mf.content)
    end
  end
  fields.to_a
end

#merge(replacements = {}) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/docx_tools/mail_merge.rb', line 23

def merge(replacements = {})
  part_list.each_part do |part|
    replacements.each do |field, text|
      merge_field(part, field, text)
    end
  end
end

#write(filename) ⇒ Object



31
32
33
34
35
# File 'lib/docx_tools/mail_merge.rb', line 31

def write(filename)
  File.open(filename, 'w') do |file|
    file.write(generate.string)
  end
end