Skip to content

Commit

Permalink
Merge pull request #75 from misdoro/text_run_gsub!
Browse files Browse the repository at this point in the history
Implement substitute method on TextRun class
  • Loading branch information
satoryu committed Dec 31, 2019
2 parents 3e67745 + 92fed2d commit bb823da
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ doc.paragraphs.each do |p|
p.remove! if p.to_s =~ /TODO/
end

# Substitute text, preserving formatting
doc.paragraphs.each do |p|
p.each_text_run do |tr|
tr.substitute('_placeholder_', 'replacement value')
end
end

# Save document to specified path
doc.save('example-edited.docx')
```
Expand Down
7 changes: 7 additions & 0 deletions lib/docx/containers/text_run.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ def parse_text
@text_nodes.map(&:content).join('')
end

# Substitute text in text @text_nodes
def substitute(match, replacement)
@text_nodes.each do |text_node|
text_node.content = text_node.content.gsub(match, replacement)
end
end

def parse_formatting
{
italic: !@node.xpath('.//w:i').empty?,
Expand Down
18 changes: 18 additions & 0 deletions spec/docx/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,24 @@
end
end

describe 'format-preserving substitution' do
before do
@doc = Docx::Document.open(@fixtures_path + '/substitution.docx')
end

it 'should replace placeholder in any line of a paragraph' do
expect(@doc.paragraphs[0].text).to eq('Page title')
expect(@doc.paragraphs[1].text).to eq('Multi-line paragraph line 1_placeholder2_ line 2_placeholder3_ line3 ')

@doc.paragraphs[1].each_text_run do |text_run|
text_run.substitute('_placeholder2_', 'same paragraph')
text_run.substitute('_placeholder3_', 'yet the same paragraph')
end

expect(@doc.paragraphs[1].text).to eq('Multi-line paragraph line 1same paragraph line 2yet the same paragraph line3 ')
end
end

describe 'read formatting' do
before do
@doc = Docx::Document.open(@fixtures_path + '/formatting.docx')
Expand Down
Binary file added spec/fixtures/substitution.docx
Binary file not shown.

0 comments on commit bb823da

Please sign in to comment.