Class: Creek::SharedStrings

Inherits:
Object
  • Object
show all
Defined in:
lib/creek/shared_strings.rb

Constant Summary collapse

SPREADSHEETML_URI =
'http://schemas.openxmlformats.org/spreadsheetml/2006/main'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(book) ⇒ SharedStrings

Returns a new instance of SharedStrings.



14
15
16
17
# File 'lib/creek/shared_strings.rb', line 14

def initialize book
  @book = book
  parse_shared_shared_strings
end

Instance Attribute Details

#bookObject (readonly)

Returns the value of attribute book.



12
13
14
# File 'lib/creek/shared_strings.rb', line 12

def book
  @book
end

#dictionaryObject (readonly)

Returns the value of attribute dictionary.



12
13
14
# File 'lib/creek/shared_strings.rb', line 12

def dictionary
  @dictionary
end

Class Method Details

.parse_shared_string_from_document(xml) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/creek/shared_strings.rb', line 32

def self.parse_shared_string_from_document(xml)
  dictionary = Hash.new
  namespace = xml.namespaces.detect{|_key, uri| uri == SPREADSHEETML_URI }
  prefix = if namespace && namespace[0].start_with?('xmlns:')
             namespace[0].delete_prefix('xmlns:') + '|'
           else
             ''
           end
  node_selector = "#{prefix}si"
  text_selector = ">#{prefix}t, #{prefix}r #{prefix}t"

  xml.css(node_selector).each_with_index do |si, idx|
    text_nodes = si.css(text_selector)
    if text_nodes.count == 1 # plain text node
      dictionary[idx] = Creek::Styles::Converter.unescape_string(text_nodes.first.content)
    else # rich text nodes with text fragments
      dictionary[idx] = text_nodes.map { |n| Creek::Styles::Converter.unescape_string(n.content) }.join('')
    end
  end

  dictionary
end

Instance Method Details

#parse_shared_shared_stringsObject



19
20
21
22
23
24
25
26
# File 'lib/creek/shared_strings.rb', line 19

def parse_shared_shared_strings
  path = "xl/sharedStrings.xml"
  if @book.files.file.exist?(path)
    doc = @book.files.file.open path
    xml = Nokogiri::XML::Document.parse doc
    parse_shared_string_from_document(xml)
  end
end

#parse_shared_string_from_document(xml) ⇒ Object



28
29
30
# File 'lib/creek/shared_strings.rb', line 28

def parse_shared_string_from_document(xml)
  @dictionary = self.class.parse_shared_string_from_document(xml)
end