Skip to content
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
3 changes: 2 additions & 1 deletion lib/docx/elements/element.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ def append_to(element)

# Insert node as first child (after properties)
def prepend_to(element)
@node = element.node.properties.add_next_sibling(@node)
properties = element.properties if element.respond_to?(:properties)
@node = properties ? properties.add_next_sibling(@node) : element.node.prepend_child(@node)
self
end

Expand Down
30 changes: 30 additions & 0 deletions spec/docx/elements/element_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,36 @@ def texts
end
end

# Regression tests for #189
describe '#prepend_to' do
let(:run) { element_class.new(w_node('<w:r><w:t>new </w:t></w:r>')) }

it 'inserts the node right after the properties of a container' do
paragraph = Docx::Elements::Containers::Paragraph.new(
w_node('<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>text</w:t></w:r></w:p>')
)

expect(run.prepend_to(paragraph)).to equal(run)
expect(paragraph.node.element_children.map(&:name)).to eq(%w[pPr r r])
expect(paragraph.text).to eq('new text')
expect(run.node.parent).to equal(paragraph.node)
end

it 'inserts the node as the first child of a container without properties' do
paragraph = Docx::Elements::Containers::Paragraph.new(w_node('<w:p><w:r><w:t>text</w:t></w:r></w:p>'))

run.prepend_to(paragraph)

expect(paragraph.text).to eq('new text')
end

it 'inserts the node as the first child of a non-container element' do
run.prepend_to(first)

expect(texts).to eq(%w[new\ first second])
end
end

describe '.create_with' do
it 'builds a detached element from the class tag in the same XML document' do
created = element_class.create_with(first)
Expand Down
Loading