Class: OpenXml::Parts::ContentTypes

Inherits:
OpenXml::Part show all
Defined in:
lib/openxml/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.


25
26
27
28
# File 'lib/openxml/parts/content_types.rb', line 25

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

Instance Attribute Details

#defaultsObject (readonly)

Returns the value of attribute defaults


6
7
8
# File 'lib/openxml/parts/content_types.rb', line 6

def defaults
  @defaults
end

#overridesObject (readonly)

Returns the value of attribute overrides


6
7
8
# File 'lib/openxml/parts/content_types.rb', line 6

def overrides
  @overrides
end

Class Method Details

.parse(xml) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
# File 'lib/openxml/parts/content_types.rb', line 13

def self.parse(xml)
  document = Nokogiri::XML(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


30
31
32
# File 'lib/openxml/parts/content_types.rb', line 30

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

#add_override(part_name, content_type) ⇒ Object


34
35
36
# File 'lib/openxml/parts/content_types.rb', line 34

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

#of(path) ⇒ Object


38
39
40
# File 'lib/openxml/parts/content_types.rb', line 38

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

#to_xmlObject


42
43
44
45
46
47
48
49
# File 'lib/openxml/parts/content_types.rb', line 42

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