Class: RubyXL::ContentTypes

Inherits:
OOXMLTopLevelObject show all
Defined in:
lib/rubyXL/objects/content_types.rb

Constant Summary collapse

SAVE_ORDER =

Must be saved last, so it has time to accumulate overrides from all others.

999

Constants inherited from OOXMLTopLevelObject

OOXMLTopLevelObject::ROOT

Instance Attribute Summary

Attributes inherited from OOXMLTopLevelObject

#root

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from OOXMLTopLevelObject

#add_to_zip, #file_index, parse_file, set_namespaces

Methods included from OOXMLObjectInstanceMethods

#dup, included, #index_in_collection, #initialize, #write_xml

Class Method Details

.xlsx_pathObject



26
27
28
# File 'lib/rubyXL/objects/content_types.rb', line 26

def self.xlsx_path
  ROOT.join('[Content_Types].xml')
end

Instance Method Details

#before_write_xmlObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rubyXL/objects/content_types.rb', line 34

def before_write_xml
  content_types_by_ext = {}

  # Collect all extensions and corresponding content types
  root.rels_hash.each_pair { |klass, objects|
    objects.each { |obj|
      next unless klass.const_defined?(:CONTENT_TYPE)
      ext = obj.xlsx_path.extname[1..-1]
      next if ext.nil?
      content_types_by_ext[ext] ||= []
      content_types_by_ext[ext] << klass::CONTENT_TYPE 
    }
  }

  self.defaults = [ RubyXL::ContentTypeDefault.new(:extension => 'xml', :content_type => 'application/xml') ]

  # Determine which content types are used most often, and add them to the list of defaults
  content_types_by_ext.each_pair { |ext, content_types_arr|
    next if ext.nil? || defaults.any? { |d| d.extension == ext } 

    counter = {}  # Count the number of occurrences of a given +content_type+.
    content_types_arr.each { |ct| counter[ct] = (counter[ct] || 0) + 1 }
    most_used_content_type = counter.to_a.max_by{ |pair| pair.last }.first

    defaults << RubyXL::ContentTypeDefault.new(:extension => ext,
                                               :content_type => most_used_content_type)
  }

  self.overrides = []

  # Add overrides for the files with known extensions but different content types.
  root.rels_hash.each_pair { |klass, objects|
    objects.each { |obj|
      next unless defined?(klass::CONTENT_TYPE)
      ext = obj.xlsx_path.extname[1..-1]
      next if ext.nil?
      next if defaults.any? { |d| (d.content_type == klass::CONTENT_TYPE) && (d.extension == ext) }
      overrides << RubyXL::ContentTypeOverride.new(:part_name => obj.xlsx_path,
                                                   :content_type => klass::CONTENT_TYPE)
    }
  }

  true
end

#xlsx_pathObject



30
31
32
# File 'lib/rubyXL/objects/content_types.rb', line 30

def xlsx_path
  self.class.xlsx_path
end