Class: Docxgen::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/docxgen/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ Generator

Returns a new instance of Generator.



10
11
12
13
14
# File 'lib/docxgen/generator.rb', line 10

def initialize(document)
  @doc = Docx::Document.open(document)
  @errors = []
  @rendered = false
end

Instance Attribute Details

#docObject (readonly)

Returns the value of attribute doc.



8
9
10
# File 'lib/docxgen/generator.rb', line 8

def doc
  @doc
end

Instance Method Details

#errorsObject



36
37
38
39
40
# File 'lib/docxgen/generator.rb', line 36

def errors
  raise "Wasn't rendered" unless @rendered

  @errors
end

#render(data, remove_missing: true) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/docxgen/generator.rb', line 16

def render(data, remove_missing: true)
  raise "Already rendered" if @rendered

  variables = JSON.parse(data.to_json, symbolize_names: true)

  paragraphs = @doc.paragraphs + collect_table_paragraphs

  paragraphs.each do |p|
    p.each_text_run do |tr|
      _, sub_errors = Templates::Parser.tr_substitute!(tr, variables, remove_missing: remove_missing)

      @errors.push(*sub_errors)
    end
  end

  @rendered = true

  valid?
end

#save(to) ⇒ Object



46
47
48
49
50
# File 'lib/docxgen/generator.rb', line 46

def save(to)
  raise "Wasn't rendered" unless @rendered

  @doc.save(to)
end

#streamObject



52
53
54
55
56
# File 'lib/docxgen/generator.rb', line 52

def stream
  raise "Wasn't rendered" unless @rendered

  @doc.stream
end

#valid?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/docxgen/generator.rb', line 42

def valid?
  errors.size.zero?
end