Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement substitute method on TextRun class #75

Merged
merged 1 commit into from
Dec 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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: [email protected]('.//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.