Skip to content

Commit

Permalink
handle w:fldSimple with extra runs.
Browse files Browse the repository at this point in the history
Closes senny#32.

It's possible that a simple field contains more than a single `w:r`
tag. Previously sablon would replace the text of the first `w:r` to
reuse it's formatting and keep all additional `w:r` as is. The result
was half-replaced fields that still contained leftovers from the merge
fields display.

This patch removes all extra `w:r` tags.
  • Loading branch information
senny committed Sep 3, 2016
1 parent 27ae531 commit 9e1c094
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/sablon/parser/mail_merge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def initialize(node)
end

def replace(content)
remove_extra_runs!
replace_field_display(@node, content)
@node.replace(@node.children)
end
Expand All @@ -89,6 +90,11 @@ def start_node
@node
end
alias_method :end_node, :start_node

private
def remove_extra_runs!
@node.search(".//w:r")[1..-1].each(&:remove)
end
end

def parse_fields(xml)
Expand Down
20 changes: 20 additions & 0 deletions test/fixtures/xml/simple_field_with_styling.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<w:p>
<w:r><w:t xml:space="preserve">Generated by </w:t></w:r>
<w:fldSimple w:instr=" MERGEFIELD =system_name \* MERGEFORMAT ">
<w:r w:rsidR="002D39A9">
<w:rPr>
<w:rFonts w:hint="eastAsia"/>
<w:noProof/>
</w:rPr>
<w:t>«</w:t>
</w:r>
<w:r w:rsidR="002D39A9">
<w:rPr><w:noProof/></w:rPr>
<w:t>=system_name</w:t>
</w:r>
<w:r w:rsidR="002D39A9">
<w:rPr><w:rFonts w:hint="eastAsia"/><w:noProof/></w:rPr>
<w:t>»</w:t>
</w:r>
</w:fldSimple>
</w:p>
18 changes: 18 additions & 0 deletions test/processor/document_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ def test_simple_field_replacement_with_nil
document
end

def test_simple_field_with_styling_replacement
result = process(snippet("simple_field_with_styling"), {"system_name" => "Sablon 1 million"})

assert_equal "Generated by Sablon 1 million", text(result)
assert_xml_equal <<-document, result
<w:p>
<w:r><w:t xml:space="preserve">Generated by </w:t></w:r>
<w:r w:rsidR="002D39A9">
<w:rPr>
<w:rFonts w:hint="eastAsia"/>
<w:noProof/>
</w:rPr>
<w:t>Sablon 1 million</w:t>
</w:r>
</w:p>
document
end

def test_context_can_contain_string_and_symbol_keys
result = process(snippet("simple_fields"), {"first_name" => "Jack", last_name: "Davis"})
assert_equal "Jack Davis", text(result)
Expand Down

0 comments on commit 9e1c094

Please sign in to comment.