Class: OpenXml::Parts::ContentTypes

Inherits:
OpenXml::Part show all
Defined in:
lib/open_xml/parts/content_types.rb

Constant Summary collapse

REQUIRED_DEFAULTS =
{
  "xml" => Types::XML,
  "rels" => Types::RELATIONSHIPS
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from OpenXml::Part

#build_standalone_xml, #build_xml, #read

Constructor Details

#initialize(defaults = {}, overrides = {}) ⇒ ContentTypes

Returns a new instance of ContentTypes.



23
24
25
26
# File 'lib/open_xml/parts/content_types.rb', line 23

def initialize(defaults={}, overrides={})
  @defaults = REQUIRED_DEFAULTS.merge(defaults)
  @overrides = overrides
end

Instance Attribute Details

#defaultsObject (readonly)

Returns the value of attribute defaults.



4
5
6
# File 'lib/open_xml/parts/content_types.rb', line 4

def defaults
  @defaults
end

#overridesObject (readonly)

Returns the value of attribute overrides.



4
5
6
# File 'lib/open_xml/parts/content_types.rb', line 4

def overrides
  @overrides
end

Class Method Details

.parse(xml) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/open_xml/parts/content_types.rb', line 11

def self.parse(xml)
  document = Nokogiri(xml)
  self.new.tap do |part|
    document.css("Default").each do |default|
      part.add_default default["Extension"], default["ContentType"]
    end
    document.css("Override").each do |default|
      part.add_override default["PartName"], default["ContentType"]
    end
  end
end

Instance Method Details

#add_default(extension, content_type) ⇒ Object



28
29
30
# File 'lib/open_xml/parts/content_types.rb', line 28

def add_default(extension, content_type)
  defaults[extension] = content_type
end

#add_override(part_name, content_type) ⇒ Object



32
33
34
# File 'lib/open_xml/parts/content_types.rb', line 32

def add_override(part_name, content_type)
  overrides[part_name] = content_type
end

#of(path) ⇒ Object



36
37
38
# File 'lib/open_xml/parts/content_types.rb', line 36

def of(path)
  overrides.fetch(path, defaults[File.extname(path)[1..-1]])
end

#to_xmlObject



40
41
42
43
44
45
46
47
# File 'lib/open_xml/parts/content_types.rb', line 40

def to_xml
  build_xml do |xml|
    xml.Types(xmlns: "http://schemas.openxmlformats.org/package/2006/content-types") {
      defaults.each { |extension, content_type| xml.Default("Extension" => extension, "ContentType" => content_type) }
      overrides.each { |part_name, content_type| xml.Override("PartName" => part_name, "ContentType" => content_type) }
    }
  end
end