Class: Commenter::Filler

Inherits:
Object
  • Object
show all
Defined in:
lib/commenter/filler.rb

Instance Method Summary collapse

Instance Method Details

#fill(template_path, output_path, comments, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/commenter/filler.rb', line 7

def fill(template_path, output_path, comments, options = {})
  doc = Docx::Document.open(template_path)
  table = doc.tables.first

  raise "No table found in template" unless table
  raise "Template table must have at least one row" if table.row_count < 1

  # Get the template row (first row in the table)
  template_row = table.rows.first

  # Add new rows for each comment by copying the template row
  comments.each_with_index do |comment, _index|
    # Convert comment to symbol keys for consistent access
    comment_data = symbolize_keys(comment)

    # Copy the template row and insert it
    begin
      new_row = template_row.copy
      new_row.insert_before(template_row)
      row = new_row
    rescue StandardError => e
      puts "Warning: Could not add row for comment #{comment_data[:id]}: #{e.message}"
      next
    end

    # Map comment to table cells using text substitution
    set_cell_text(row.cells[0], comment_data[:id] || "")
    set_cell_text(row.cells[1], comment_data.dig(:locality, :line_number) || "")
    set_cell_text(row.cells[2], comment_data.dig(:locality, :clause) || "")
    set_cell_text(row.cells[3], comment_data.dig(:locality, :element) || "")
    set_cell_text(row.cells[4], comment_data[:type] || "")
    set_cell_text(row.cells[5], comment_data[:comments] || "")
    set_cell_text(row.cells[6], comment_data[:proposed_change] || "")

    # Handle observations with optional shading
    observations = comment_data[:observations]
    if observations && !observations.empty?
      set_cell_text(row.cells[7], observations)
      apply_shading(row.cells[7], observations) if options[:shading]
    end
  end

  # Remove the original template row after all comments are added
  template_row.remove if template_row.respond_to?(:remove)

  doc.save(output_path)
end