Class: Sheng::Docx

Inherits:
Object
  • Object
show all
Defined in:
lib/sheng/docx.rb

Defined Under Namespace

Classes: InvalidFile, MergeError, OutputPathAlreadyExists, TemplateError

Constant Summary collapse

WMLFileNamePatterns =
[
  /word\/document.xml/,
  /word\/numbering.xml/,
  /word\/header(\d)*.xml/,
  /word\/footer(\d)*.xml/
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_file_path, params) ⇒ Docx

Returns a new instance of Docx.



21
22
23
24
25
26
27
# File 'lib/sheng/docx.rb', line 21

def initialize(input_file_path, params)
  @input_zip_file = Zip::File.new(input_file_path)
  @data_set = DataSet.new(params)
  @errors = {}
rescue Zip::Error => e
  raise InvalidFile.new(e.message)
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



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

def errors
  @errors
end

Instance Method Details

#generate(path, force: false) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/sheng/docx.rb', line 45

def generate(path, force: false)
  if File.exists?(path) && !force
    raise OutputPathAlreadyExists, "File at #{path} already exists"
  end

  output_buffer = generate_output_buffer

  if errors.present?
    raise MergeError.new(errors)
  end

  File.open(path, "w") { |f| f.write(output_buffer.string) }
end

#required_hashObject



41
42
43
# File 'lib/sheng/docx.rb', line 41

def required_hash
  wml_files.inject({}) { |memo, wml| Sheng::Support.merge_required_hashes(memo, wml.required_hash) }
end

#to_treeObject



37
38
39
# File 'lib/sheng/docx.rb', line 37

def to_tree
  wml_files.map { |wml| { :file => wml.filename, :tree => wml.to_tree } }
end

#wml_filesObject



29
30
31
32
33
34
35
# File 'lib/sheng/docx.rb', line 29

def wml_files
  @wml_files ||= @input_zip_file.entries.map do |entry|
    if is_wml_file?(entry.name)
      WMLFile.new(entry.name, entry.get_input_stream)
    end
  end.compact
end