Class: DocxManipulator

Inherits:
Object
  • Object
show all
Defined in:
lib/docx_manipulator.rb,
lib/docx_manipulator/content.rb,
lib/docx_manipulator/version.rb,
lib/docx_manipulator/relationships.rb

Defined Under Namespace

Classes: Content, Relationships

Constant Summary collapse

VERSION =
"0.0.8"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, target) ⇒ DocxManipulator

Returns a new instance of DocxManipulator.



11
12
13
14
15
16
17
# File 'lib/docx_manipulator.rb', line 11

def initialize(source, target)
  @source = source
  @target = target

  @changed_files = []
  @relationships = Relationships.new(source)
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



9
10
11
# File 'lib/docx_manipulator.rb', line 9

def source
  @source
end

#targetObject (readonly)

Returns the value of attribute target.



9
10
11
# File 'lib/docx_manipulator.rb', line 9

def target
  @target
end

Instance Method Details

#add_binary_image(id, name, data) ⇒ Object



35
36
37
# File 'lib/docx_manipulator.rb', line 35

def add_binary_image(id, name, data)
  @relationships.add_binary_image(id, name, data)
end

#add_file(path, data, options = {}) ⇒ Object



23
24
25
# File 'lib/docx_manipulator.rb', line 23

def add_file(path, data, options = {})
  @changed_files << Content.new(path, data, options)
end

#add_image(id, path) ⇒ Object



27
28
29
# File 'lib/docx_manipulator.rb', line 27

def add_image(id, path)
  @relationships.add_image(id, path)
end

#add_relationship(id, type, target, attributes = {}) ⇒ Object



31
32
33
# File 'lib/docx_manipulator.rb', line 31

def add_relationship(id, type, target, attributes = {})
  @relationships.add_node(id, type, target, attributes)
end

#content(new_content, options = {}) ⇒ Object



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

def content(new_content, options = {})
  @changed_files << Content.new('word/document.xml', new_content, options)
end

#processObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/docx_manipulator.rb', line 39

def process
  files_to_be_written = @changed_files.map(&:writes_to_file).flatten + @relationships.writes_to_files

  Zip::ZipOutputStream.open(target) do |os|
    Zip::ZipFile.foreach(source) do |entry|
      if !files_to_be_written.include?(entry.name) && entry.file?
        os.put_next_entry entry.name
        os.write entry.get_input_stream.read
      end
    end

    @changed_files.each {|f| f.process(os)}
    @relationships.process(os)
  end
end