Class: OpenXml::Package

Inherits:
Object
  • Object
show all
Defined in:
lib/openxml/package.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(zipfile = nil) ⇒ Package

Returns a new instance of Package.



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

def initialize(zipfile=nil)
  @zipfile = zipfile
  @parts = {}

  set_defaults
  read_zipfile! if zipfile
end

Instance Attribute Details

#content_types ⇒ Object (readonly)

Returns the value of attribute content_types.



10
11
12
# File 'lib/openxml/package.rb', line 10

def content_types
  @content_types
end

#parts ⇒ Object (readonly)

Returns the value of attribute parts.



10
11
12
# File 'lib/openxml/package.rb', line 10

def parts
  @parts
end

#rels ⇒ Object (readonly)

Returns the value of attribute rels.



10
11
12
# File 'lib/openxml/package.rb', line 10

def rels
  @rels
end

Class Method Details

.content_types(&block) ⇒ Object



19
20
21
# File 'lib/openxml/package.rb', line 19

def content_types(&block)
  content_types_presets.instance_eval(&block)
end

.content_types_presets ⇒ Object



15
16
17
# File 'lib/openxml/package.rb', line 15

def content_types_presets
  @content_types_presets ||= OpenXml::ContentTypesPresets.new
end

.from_stream(stream) ⇒ Object



33
34
35
36
37
# File 'lib/openxml/package.rb', line 33

def from_stream(stream)
  stream = StringIO.new(stream) if stream.is_a?(String)
  zipfile = ::Zip::File.new(stream, create: true, buffer: true)
  new(zipfile)
end

.open(path) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/openxml/package.rb', line 23

def open(path)
  if block_given?
    Zip::File.open(path) do |zipfile|
      yield new(zipfile)
    end
  else
    new Zip::File.open(path)
  end
end

Instance Method Details

#add_part(path, part) ⇒ Object



52
53
54
# File 'lib/openxml/package.rb', line 52

def add_part(path, part)
  @parts[path] = part
end

#close ⇒ Object



67
68
69
# File 'lib/openxml/package.rb', line 67

def close
  zipfile.close if zipfile
end

#get_part(path) ⇒ Object



56
57
58
# File 'lib/openxml/package.rb', line 56

def get_part(path)
  @parts.fetch(path)
end

#to_stream ⇒ Object



78
79
80
81
82
83
84
85
# File 'lib/openxml/package.rb', line 78

def to_stream
  Zip::OutputStream.write_buffer do |io|
    parts.each do |path, part|
      io.put_next_entry path
      io.write part.content
    end
  end
end

#type_of(path) ⇒ Object



60
61
62
63
# File 'lib/openxml/package.rb', line 60

def type_of(path)
  raise Errors::MissingContentTypesPart, "We haven't yet read [ContentTypes].xml; but are reading #{path.inspect}" unless content_types
  content_types.of(path)
end

#write_to(path) ⇒ Object Also known as: save



71
72
73
74
75
# File 'lib/openxml/package.rb', line 71

def write_to(path)
  File.open(path, "wb") do |file|
    file.write to_stream.string
  end
end