Class: OdtHandlebars::OdtFill

Inherits:
Object
  • Object
show all
Defined in:
lib/odt_handlebars/odt_fill.rb

Constant Summary collapse

FIELD_MATCHER =
Regexp.new("{{.+?}}",Regexp::MULTILINE)

Instance Method Summary collapse

Constructor Details

#initialize(infile, outfile, fill) ⇒ OdtFill

Returns a new instance of OdtFill.



9
10
11
12
13
# File 'lib/odt_handlebars/odt_fill.rb', line 9

def initialize(infile,outfile,fill)
  @infile=infile
  @outfile=outfile
  @fill=fill
end

Instance Method Details

#replaceObject



15
16
17
# File 'lib/odt_handlebars/odt_fill.rb', line 15

def replace
  unpack
end

#replace_handlebars(raw_content, placeholders) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/odt_handlebars/odt_fill.rb', line 42

def replace_handlebars(raw_content,placeholders)
  content=OdtCleaner.clean(raw_content)
  doc=Nokogiri.parse(content)
  rows=doc.xpath("//table:table-row/*[starts-with(.,'{{/each')]")
  rows.each do |row| row.parent.replace(row.to_str) end
  rows=doc.xpath("//table:table-row/*[starts-with(.,'{{#each')]")
  rows.each do |row| row.parent.replace(row.to_str) end
  fields=doc.xpath("//text:p/*")
  handlebars = Handlebars::Context.new
  template = handlebars.compile(doc.to_s)
  out=template.call(placeholders)
  out
end

#unpackObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/odt_handlebars/odt_fill.rb', line 19

def unpack
  File.open(@outfile,"w") do |outfile|
    Zip::OutputStream.write_buffer(outfile) do |outzip|
      Zip::File.open(@infile) do |inzip|
        inzip.entries.each do |e|
          next if e.file_type_is?(:directory)
          if e.name == "content.xml"
            content = e.get_input_stream.read
            output=replace_handlebars(content,@fill)
            outzip.put_next_entry(e.name)
            outzip.write output
          else
            outzip.put_next_entry(e.name)
            outzip.write e.get_input_stream.read
          end
        end
      end
    end
  end
  @outfile
end