From 9c9bbc8d997afef28968e0c844f3c7e10129851e Mon Sep 17 00:00:00 2001 From: JP Slavinsky Date: Fri, 29 Apr 2016 22:04:49 -0700 Subject: [PATCH] Cache author info in Comment classes --- lib/axlsx/workbook/worksheet/comment.rb | 3 +-- lib/axlsx/workbook/worksheet/comments.rb | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/axlsx/workbook/worksheet/comment.rb b/lib/axlsx/workbook/worksheet/comment.rb index e5dbe41c..3f84fba5 100644 --- a/lib/axlsx/workbook/worksheet/comment.rb +++ b/lib/axlsx/workbook/worksheet/comment.rb @@ -47,7 +47,7 @@ def vml_shape # the comment. # @return [Integer] def author_index - @comments.authors.index(author) + @comments.author_index(author) end # @see ref @@ -61,7 +61,6 @@ def ref=(v) # @param [String] str # @return [String] def to_xml_string(str = "") - author = @comments.authors[author_index] str << ('') str << '' unless author.to_s == "" diff --git a/lib/axlsx/workbook/worksheet/comments.rb b/lib/axlsx/workbook/worksheet/comments.rb index dfc6d143..c45d8c31 100644 --- a/lib/axlsx/workbook/worksheet/comments.rb +++ b/lib/axlsx/workbook/worksheet/comments.rb @@ -44,13 +44,21 @@ def add_comment(options={}) raise ArgumentError, "Comment requires ref" unless options[:ref] self << Comment.new(self, options) yield last if block_given? + clear_author_caches last end # A sorted list of the unique authors in the contained comments # @return [Array] def authors - map { |comment| comment.author.to_s }.uniq.sort + @authors ||= map { |comment| comment.author.to_s }.uniq.sort + end + + # Returns the index of the given author in the sorted authors array + # @param [String] author An author + # @return [Integer] + def author_index(author) + (@author_indexes ||= {})[author] ||= authors.index(author) end # The relationships required by this object @@ -77,6 +85,13 @@ def to_xml_string(str="") end + protected + + def clear_author_caches + @authors = nil + @author_indexes = nil + end + end end