Class: Docstache::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/docstache/document.rb

Instance Method Summary collapse

Constructor Details

#initialize(*paths) ⇒ Document

Returns a new instance of Document.

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/docstache/document.rb', line 3

def initialize(*paths)
  raise ArgumentError if paths.empty?
  @path = paths.shift
  @zip_file = Zip::File.open(@path)
  load_references
  @document = Nokogiri::XML(unzip_read(@zip_file, "word/document.xml"))
  zip_files = paths.map{|p| Zip::File.open(p)}
  documents = zip_files.map{|f| Nokogiri::XML(unzip_read(f, "word/document.xml"))}
  documents.each do |doc|
    @document.css('w|p').last.add_next_sibling(page_break)
    @document.css('w|p').last.add_next_sibling(doc.css('w|body > *:not(w|sectPr)'))
  end
  find_documents_to_interpolate
end

Instance Method Details

#errors?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/docstache/document.rb', line 47

def errors?
  tags.length != usable_tags.length
end

#fix_errorsObject



41
42
43
44
45
# File 'lib/docstache/document.rb', line 41

def fix_errors
  problem_paragraphs.each do |p|
    flatten_paragraph(p) if p
  end
end

#render_file(output, data = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/docstache/document.rb', line 56

def render_file(output, data={})
  rendered_documents = Hash[
    @documents.map { |(path, document)|
      [path, Docstache::Renderer.new(document.dup, data).render]
    }
  ]
  buffer = zip_buffer(rendered_documents)
  File.open(output, "w") {|f| f.write buffer.string}
end

#render_stream(data = {}) ⇒ Object



66
67
68
69
70
71
72
73
74
75
# File 'lib/docstache/document.rb', line 66

def render_stream(data={})
  rendered_documents = Hash[
    @documents.map { |(path, document)|
      [path, Docstache::Renderer.new(document.dup, data).render]
    }
  ]
  buffer = zip_buffer(rendered_documents)
  buffer.rewind
  return buffer.sysread
end

#saveObject



51
52
53
54
# File 'lib/docstache/document.rb', line 51

def save
  buffer = zip_buffer(@documents)
  File.open(@path, "w") {|f| f.write buffer.string}
end

#tagsObject



18
19
20
21
22
# File 'lib/docstache/document.rb', line 18

def tags
  @documents.values.flat_map { |document|
    document.text.gsub(/\s+/, '').scan(/\{\{.+?\}\}/)
  }
end

#unusable_tagsObject



32
33
34
35
36
37
38
39
# File 'lib/docstache/document.rb', line 32

def unusable_tags
  unusable_tags = tags
  usable_tags.each do |usable_tag|
    index = unusable_tags.index(usable_tag)
    unusable_tags.delete_at(index) if index
  end
  return unusable_tags
end

#usable_tagsObject



24
25
26
27
28
29
30
# File 'lib/docstache/document.rb', line 24

def usable_tags
  @documents.values.flat_map { |document|
    document.css('w|t').select { |tag| tag.text =~ /\{\{.+?\}\}/ }.flat_map { |tag|
      tag.text.scan(/\{\{.+?\}\}/)
    }
  }
end