Skip to content

Commit ed0bd18

Browse files
authored
Merge pull request #112 from ruby-docx/fix-document-to_s-raises-error
Fix Docx::Document#to_s fails when given file has document22.xml.rels
2 parents e6e1e5d + e9f4266 commit ed0bd18

3 files changed

Lines changed: 22 additions & 4 deletions

File tree

lib/docx/document.rb

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,12 @@ def font_size
8787
def hyperlinks
8888
hyperlink_relationships.each_with_object({}) do |rel, hash|
8989
hash[rel.attributes['Id'].value] = rel.attributes['Target'].value
90-
end
90+
end
9191
end
9292

9393
def hyperlink_relationships
9494
@rels.xpath("//xmlns:Relationship[contains(@Type,'hyperlink')]")
95-
end
95+
end
9696

9797
##
9898
# *Deprecated*
@@ -168,13 +168,20 @@ def replace_entry(entry_path, file_contents)
168168
def load_styles
169169
@styles_xml = @zip.read('word/styles.xml')
170170
@styles = Nokogiri::XML(@styles_xml)
171-
@rels_xml = @zip.read('word/_rels/document.xml.rels')
172-
@rels = Nokogiri::XML(@rels_xml)
171+
load_rels
173172
rescue Errno::ENOENT => e
174173
warn e.message
175174
nil
176175
end
177176

177+
def load_rels
178+
rels_entry = @zip.glob('word/_rels/document*.xml.rels').first
179+
raise Errno::ENOENT unless rels_entry
180+
181+
@rels_xml = rels_entry.get_input_stream.read
182+
@rels = Nokogiri::XML(@rels_xml)
183+
end
184+
178185
#--
179186
# TODO: Flesh this out to be compatible with other files
180187
# TODO: Method to set flag on files that have been edited, probably by inserting something at the

spec/docx/document_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,4 +467,15 @@
467467
File.delete(temp_file_path) if File.exist?(temp_file_path)
468468
end
469469
end
470+
471+
describe '#to_s' do
472+
let(:doc) { Docx::Document.open(@fixtures_path + '/weird_docx.docx') }
473+
474+
it 'does not raise error' do
475+
expect { doc.to_s }.to_not raise_error
476+
end
477+
it 'returns a String' do
478+
expect(doc.to_s).to be_a(String)
479+
end
480+
end
470481
end

spec/fixtures/weird_docx.docx

13.5 KB
Binary file not shown.

0 commit comments

Comments
 (0)