diff --git a/Manifest b/Manifest index f770eb2..9424eb3 100644 --- a/Manifest +++ b/Manifest @@ -1,7 +1,12 @@ lib/odf-report.rb +lib/odf-report/report.rb +lib/odf-report/table.rb +lib/odf-report/section.rb +lib/odf-report/file_ops.rb +lib/odf-report/hash_gsub.rb odf-report.gemspec -Rakefile README.textile test/test.odt +test/sections.odt test/test.rb Manifest diff --git a/README.textile b/README.textile index 5458eb4..46f0ae3 100644 --- a/README.textile +++ b/README.textile @@ -1,24 +1,24 @@ h1. ODF-REPORT -Gem for generating .odt files by making strings, images and tables substitutions in a previously created .odt file. +Gem for generating .odt files by making strings, images, tables and sections replacements in a previously created .odt file.
-h3. INSTALL +h2. INSTALL -@gem install sandrods-odf-report --source=http://gems.github.com@ +(sudo) gem install odf-report
-h3. USAGE +h2. USAGE -h4. Step 1 -- the template +h3. Step 1 -- the template First of all, you need to create a .odt file to serve as a template Templates are normal .odt files with placeholders for Substitutions -There are now three kinds of substitutions available: *fields*, *tables* and *images*. +There are now *four* kinds of substitutions available: *fields*, *tables*, *images* and *sections*. h4. Fields placeholders @@ -27,11 +27,11 @@ It's just an upcase sentence, surrounded by brackets. It will be replaced for wa In the folowing example:
-report = ODFReport.new("Users/john/my_template.odt") do |r|
+report = ODFReport::Report.new("Users/john/my_template.odt") do |r|
 
   r.add_field :user_name, @user.name
   r.add_field :address, "My new address"
-  
+
 end
 
@@ -43,21 +43,21 @@ h4. Table placeholders To use table placeholders, you should create a Table in your document and give it a name. In OpenOffice, it's just a matter of right-clicking the table you just created, choose _Table Properties..._ and type a name in the Name field. -If the table has two rows, the first one will be treated as a *header* and left untouched. Otherwise you should use a table with one row only. +If you inform @:header=>true@, the first row will be treated as a *header* and left untouched. The remaining rows will be used as the template for the table. If you have more than one template row, they will be cycled. This is usefull for making zebra tables. As with Field placeholders, just insert a @[FIELD_NAME]@ in each cell and let the magic takes place. Taking the folowing example:
-report = ODFReport.new("Users/john/my_template.odt") do |r|
+report = ODFReport::Report.new("Users/john/my_template.odt") do |r|
 
   r.add_field "USER_NAME", @user.nome
   r.add_field "ADDRESS", @user.address
 
-  r.add_table("TABLE_1", @list_of_itens) do |row, item|
-    row["ITEM_ID"] = item.id
-    row["DESCRIPTION"] = "==> #{item.description}"
+  r.add_table("TABLE_1", @list_of_itens, :header=>true) do |t|
+    t.add_column(:item_id, :id)
+    t.add_column(:description) do { |item| "==> #{item.description}" }
   end
 
 end
@@ -70,9 +70,9 @@ and considering you have a table like this in your template
 |  [ITEM_ID]  |  [DESCRIPTION]  |
 ---------------------------------
 
-* this is my lame attempt to draw a table. 
-  you don't suppose to type this. 
-  you have to use an actual table. 
+* this is my lame attempt to draw a table.
+  you don't suppose to type this.
+  you have to use an actual table.
   i don't know... just thought I'd mention it ;-)
 
@@ -88,61 +88,98 @@ You can also assign any properties you want to the mock image and they will be k An image replace would look like this:
-report = ODFReport.new("Users/john/my_template.odt") do |r|
+report = ODFReport::Report.new("Users/john/my_template.odt") do |r|
 
   r.add_image :graphics1, "/path/to/the/image.jpg"
 
 end
 
-And that's it. +h4. Sections (NEW!) + +Sometimes, you have to repeat a whole chunk of a document, in a structure a lot more complex than a table. Now you can make a Section in your template and use it in this situations. Creating a Session in OpenOffice is as easy as select menu *Insert* and then *Section...*, and then choose a name for it. + +*Section*'s are lot like Tables, in the sense that you can pass a collection and have that section repeated for each member of the collection. *But*, Sections can have anything inside it, even Tables, as long as you pass the appropriate data structure. + +Let's see an example: + +
+
+  @invoices = Invoice.find(:all)
+
+  report = ODFReport::Report.new("reports/invoice.odt") do |r|
+
+    r.add_field(:title, "INVOICES REPORT")
+    r.add_field(:date, Date.today)
+
+    r.add_section("SC_INVOICE", @invoices) do |s|
+
+      s.add_field(:number) { |invoice| invoice.number.to_s.rjust(5, '0') }
+      s.add_field(:name,    :customer_name)
+      s.add_field(:address, :customer_address)
+
+      s.add_table("TB_ITEMS", :items, :header => true) do |t|
+        t.add_column(:id)
+        t.add_column(:product) {|item| item.product.name }
+        t.add_column(:value, :product_value)
+      end
+
+      s.add_field(:total) do |invoice|
+        if invoice.status == 'CLOSED'
+          invoice.total
+        else
+          invoice.items.sum('product_value')}
+        end
+      end
+
+    end
+
+  end
+
+ +Note that when you add a Table to a Section, you don't pass the collection itself, but the attribute of the item of that section that's gonna return the collection for that particular Table. Sounds complicated, huh? But once you get it, it's quite straightforward. + +In the above example, @s.add_table("TB_ITEMS", :items, :header => true) do |t|@, the @:items@ thing refers to a @invoice.items@. Easy, right?

-h4. Step 2 -- generating the document +h3. Step 2 -- generating the document It's fairly simple to generate the document. You can use this inside a Rails application or in a standalone script. -h4. Generating a document in a Rails application +h4. Generating a document in a Rails application In a controller, you can have a code like this: - +
 def print
 
   @ticket = Ticket.find(params[:id])
 
-  report = ODFReport.new("#{RAILS_ROOT}/app/reports/ticket.odt") do |r|
-   
-    r.add_field(:id, @ticket.id.to_s)
+  report = ODFReport::Report.new("#{RAILS_ROOT}/app/reports/ticket.odt") do |r|
+
+    r.add_field(:id,         @ticket.id.to_s)
     r.add_field(:created_by, @ticket.created_by)
     r.add_field(:created_at, @ticket.created_at.strftime("%d/%m/%Y - %H:%M"))
-    r.add_field(:type, @ticket.type.name)
-    r.add_field(:status, @ticket.status_text)
-    r.add_field(:date, Time.now.strftime("%d/%m/%Y - %H:%M"))
-    r.add_field(:solution, (@ticket.solution || ''))
+    r.add_field(:type,       @ticket.type.name)
+    r.add_field(:status,     @ticket.status_text)
+    r.add_field(:date,       Time.now.strftime("%d/%m/%Y - %H:%M"))
+    r.add_field(:solution,   (@ticket.solution || ''))
 
-    r.add_table("OPERATORS", @ticket.operators) do | row, op |
-      row["OPERATOR_NAME"] = "#{op.name} (#{op.department.short_name})"
+    r.add_table("OPERATORS", @ticket.operators) do |t|
+      t.add_column(:operator_name) { |op| "#{op.name} (#{op.department.short_name})" }
     end
-   
-    r.add_table("FIELDS", @ticket.fields) do | row, field |
-     
-      if field.is_a?(String)
-        row["FIELD_NAME"] = 'Materials'
-        row["FIELD_VALUE"] = field
-      else
-        row["FIELD_NAME"] = field.name
-        row["FIELD_VALUE"] = field.text_value || ''
-      end
 
+    r.add_table("FIELDS", @ticket.fields) do |t|
+      t.add_column(:field_name, :name)
+      t.add_column(:field_value) { |field| field.text_value || "Empty" }
     end
 
   end
 
   report_file_name = report.generate
 
-  send_file(report_file_name) 
+  send_file(report_file_name)
 
 end
 
@@ -151,12 +188,12 @@ The @generate@ method will, er... generate the document in a temp dir and return _That's all I have to say about that._ -h4. Generating a document in a standalone script +h4. Generating a document in a standalone script It's just the same as in a Rails app, but you can inform the path where the file will be generated instead of using a temp dir.
-report = ODFReport.new("ticket.odt") do |r|
+report = ODFReport::Report.new("ticket.odt") do |r|
 
 ... populates the report ...
 
diff --git a/Rakefile b/Rakefile
deleted file mode 100644
index 35c17ce..0000000
--- a/Rakefile
+++ /dev/null
@@ -1,14 +0,0 @@
-require 'rubygems'
-require 'rake'
-require 'echoe'
-
-Echoe.new('odf-report', '0.1.1') do |p|
-  p.description     = "Generates ODF files, given a template (.odt) and data, replacing tags"
-  p.url             = ""
-  p.author          = "Sandro Duarte"
-  p.email           = "sandrods@gmail.com"
-  p.ignore_pattern  = ["tmp/*", "script/*"]
-  p.development_dependencies = []
-  p.runtime_dependencies = ['rubyzip >= 0.9.1']
-end
-
diff --git a/lib/odf-report.rb b/lib/odf-report.rb
index 058548a..a9b00f8 100644
--- a/lib/odf-report.rb
+++ b/lib/odf-report.rb
@@ -1,218 +1,8 @@
 require 'rubygems'
 require 'zip/zipfilesystem'
 require 'fileutils'
-
-class ODFReport
-
-  def initialize(template_name, &block)
-    @template = template_name
-    @data={:values=>{}, :tables=>{}, :images => {} }
-
-    @tmp_dir = Dir.tmpdir + "/" + random_filename(:prefix=>'odt_')
-    Dir.mkdir(@tmp_dir) unless File.exists? @tmp_dir
-
-    yield self
-  end
-
-  def add_field(field_tag, value)
-    @data[:values][field_tag] = value
-  end
-
-  def add_table(table_tag, collection, &block)
-
-    @data[:tables][table_tag] = []
-
-    collection.each do |item|
-      row = {}
-      yield(row, item)
-      @data[:tables][table_tag] << row
-    end
-
-  end
-
-  def add_image(name, path)
-    @data[:images][name] = path
-  end
-
-  def generate(dest = nil)
-
-    if dest
-
-      FileUtils.cp(@template, dest)
-      new_file = dest
-
-    else
-
-      FileUtils.cp(@template, @tmp_dir)
-      new_file = "#{@tmp_dir}/#{File.basename(@template)}"
-
-    end
-
-    %w(content.xml styles.xml).each do |content_file|
-
-      update_file_from_zip(new_file, content_file) do |txt|
-
-        replace_fields!(txt)
-        replace_tables!(txt)
-        replace_image_refs!(txt)
-      end
-
-    end
-
-    unless @data[:images].empty?
-      image_dir_name = "Pictures"
-      dir = File.join("#{@tmp_dir}", image_dir_name)
-      add_image_files_to_dir(dir)
-      add_dir_to_zip(new_file, dir, image_dir_name)
-    end
-
-    new_file
-
-  end
-
-private
-
-  def add_image_files_to_dir(dir)
-    FileUtils.mkdir(dir)
-    @data[:images].each_pair do |name, path|
-      FileUtils.cp(path, File.join(dir, File.basename(path)))
-    end
-  end
-
-  def add_dir_to_zip(zip_file, dir, entry)
-    Zip::ZipFile.open(zip_file, true) do |z|
-      Dir["#{dir}/**/*"].each { |f| z.add("#{entry}/#{File.basename(f)}", f) }
-    end
-  end
-
-  def update_file_from_zip(zip_file, content_file, &block)
-
-    Zip::ZipFile.open(zip_file) do |z|
-      cont = "#{@tmp_dir}/#{content_file}"
-
-      z.extract(content_file, cont)
-
-      txt = ''
-
-      File.open(cont, "r") do |f|
-        txt = f.read
-      end
-
-      yield(txt)
-
-      File.open(cont, "w") do |f|
-         f.write(txt)
-      end
-
-      z.replace(content_file, cont)
-    end
-
-  end
-
-
-  def replace_fields!(content)
-    hash_gsub!(content, @data[:values])
-  end
-
-  def replace_image_refs!(content)
-    @data[:images].each_pair do |image_name, path|
-      #Set the new image path
-      new_path = File.join("Pictures", File.basename(path))
-      #Search for the image
-      image_rgx = Regexp.new("draw:name=\"#{image_name}\".*?>")
-      content_match = content.match(image_rgx)
-      if content_match
-        replace_path = content_match[1]
-        content.gsub!(content_match[0], content_match[0].gsub(replace_path, new_path))
-      end
-    end
-  end
-
-  def replace_tables!(content)
-
-    @data[:tables].each do |table_name, records|
-
-      # search for the table inside the content
-      table_rgx = Regexp.new("(.*?<\/table:table>)", "m")
-      table_match = content.match(table_rgx)
-
-      if table_match
-        table = table_match[0]
-
-        # extract the table from the content
-        content.gsub!(table, "[TABLE_#{table_name}]")
-
-        # search for the table:row's
-        row_rgx = Regexp.new("()", "m")
-
-        # use scan (instead of match) as the table can have more than one table-row (header and data)
-        # and scan returns all matches
-        row_match = table.scan(row_rgx)
-
-        unless row_match.empty?
-
-          # If there more than one line in the table, takes the second entry (row_match[1])
-          # since the first one represents the column header.
-          # If there just one line, takes the first line. Besides, since the entry is an Array itself,
-          # takes the entry's first element ( entry[0] )
-          model_row = (row_match[1] || row_match[0])[0]
-
-          # extract the row from the table
-          table.gsub!(model_row, "[ROW_#{table_name}]")
-
-          new_rows = ""
-
-          # for each record
-          records.each do |_values|
-
-            # generates one new row (table-row), based in the model extracted
-            # from the original table
-            tmp_row = model_row.dup
-
-            # replace values in the model_row and stores in new_rows
-            hash_gsub!(tmp_row, _values)
-
-            new_rows << tmp_row
-          end
-
-          # replace back the lines into the table
-          table.gsub!("[ROW_#{table_name}]", new_rows)
-
-        end # unless row_match.empty?
-
-        # replace back the table into content
-        content.gsub!("[TABLE_#{table_name}]", table)
-
-      end # if table match
-
-    end # tables each
-
-  end # replace_tables
-
-  def hash_gsub!(_text, hash_of_values)
-    hash_of_values.each do |key, val|
-      _text.gsub!("[#{key.to_s.upcase}]", html_escape(val)) unless val.nil?
-    end
-  end
-
-  def random_filename(opts={})
-    opts = {:chars => ('0'..'9').to_a + ('A'..'F').to_a + ('a'..'f').to_a,
-            :length => 24, :prefix => '', :suffix => '',
-            :verify => true, :attempts => 10}.merge(opts)
-    opts[:attempts].times do
-      filename = ''
-      opts[:length].times { filename << opts[:chars][rand(opts[:chars].size)] }
-      filename = opts[:prefix] + filename + opts[:suffix]
-      return filename unless opts[:verify] && File.exists?(filename)
-    end
-    nil
-  end
-
-  HTML_ESCAPE = { '&' => '&',  '>' => '>',   '<' => '<', '"' => '"' }
-
-  def html_escape(s)
-    return "" unless s
-    s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
-  end
-
-end
+require 'odf-report/file_ops'
+require 'odf-report/hash_gsub'
+require 'odf-report/section'
+require 'odf-report/table'
+require 'odf-report/report'
diff --git a/lib/odf-report/file_ops.rb b/lib/odf-report/file_ops.rb
new file mode 100644
index 0000000..e57e97c
--- /dev/null
+++ b/lib/odf-report/file_ops.rb
@@ -0,0 +1,57 @@
+module ODFReport
+
+  module FileOps
+
+    def random_filename(opts={})
+      opts = {:chars => ('0'..'9').to_a + ('A'..'F').to_a + ('a'..'f').to_a,
+              :length => 24, :prefix => '', :suffix => '',
+              :verify => true, :attempts => 10}.merge(opts)
+      opts[:attempts].times do
+        filename = ''
+        opts[:length].times { filename << opts[:chars][rand(opts[:chars].size)] }
+        filename = opts[:prefix] + filename + opts[:suffix]
+        return filename unless opts[:verify] && File.exists?(filename)
+      end
+      nil
+    end
+
+    def add_files_to_dir(files, dir)
+      FileUtils.mkdir(dir)
+      files.each do |path|
+        FileUtils.cp(path, File.join(dir, File.basename(path)))
+      end
+    end
+
+    def add_dir_to_zip(zip_file, dir, entry)
+      Zip::ZipFile.open(zip_file, true) do |z|
+        Dir["#{dir}/**/*"].each { |f| z.add("#{entry}/#{File.basename(f)}", f) }
+      end
+    end
+
+    def update_file_from_zip(zip_file, content_file, &block)
+
+      Zip::ZipFile.open(zip_file) do |z|
+        cont = "#{@tmp_dir}/#{content_file}"
+
+        z.extract(content_file, cont)
+
+        txt = ''
+
+        File.open(cont, "r") do |f|
+          txt = f.read
+        end
+
+        yield(txt)
+
+        File.open(cont, "w") do |f|
+           f.write(txt)
+        end
+
+        z.replace(content_file, cont)
+      end
+
+    end
+
+  end
+
+end
\ No newline at end of file
diff --git a/lib/odf-report/hash_gsub.rb b/lib/odf-report/hash_gsub.rb
new file mode 100644
index 0000000..f3bcc2f
--- /dev/null
+++ b/lib/odf-report/hash_gsub.rb
@@ -0,0 +1,20 @@
+module ODFReport
+
+  module HashGsub
+
+    def hash_gsub!(_text, hash_of_values)
+      hash_of_values.each do |key, val|
+        _text.gsub!("[#{key.to_s.upcase}]", html_escape(val))
+      end
+    end
+
+    HTML_ESCAPE = { '&' => '&',  '>' => '>',   '<' => '<', '"' => '"' }
+
+    def html_escape(s)
+      return "" unless s
+      s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
+    end
+
+  end
+
+end
\ No newline at end of file
diff --git a/lib/odf-report/report.rb b/lib/odf-report/report.rb
new file mode 100644
index 0000000..e860428
--- /dev/null
+++ b/lib/odf-report/report.rb
@@ -0,0 +1,127 @@
+module ODFReport
+
+class Report
+  include HashGsub, FileOps
+
+  attr_accessor :values, :tables, :images, :sections
+
+  def initialize(template_name, &block)
+    @template = template_name
+
+    @values = {}
+    @tables = []
+    @images = {}
+    @sections = []
+
+    @tmp_dir = Dir.tmpdir + "/" + random_filename(:prefix=>'odt_')
+    Dir.mkdir(@tmp_dir) unless File.exists? @tmp_dir
+
+    yield(self)
+
+  end
+
+  def add_section(section_name, collection, &block)
+    sec = Section.new(section_name)
+    @sections << sec
+
+    yield(sec)
+
+    sec.populate(collection)
+
+  end
+
+  def add_field(field_tag, value)
+    @values[field_tag] = value || ''
+  end
+
+  def add_table(table_name, collection, opts={}, &block)
+    opts[:name] = table_name
+    tab = Table.new(opts)
+    yield(tab)
+    @tables << tab
+
+    tab.populate(collection)
+
+  end
+
+  def add_image(name, path)
+    @images[name] = path
+  end
+
+  def generate(dest = nil)
+
+    if dest
+
+      FileUtils.cp(@template, dest)
+      new_file = dest
+
+    else
+
+      FileUtils.cp(@template, @tmp_dir)
+      new_file = "#{@tmp_dir}/#{File.basename(@template)}"
+
+    end
+
+    %w(content.xml styles.xml).each do |content_file|
+
+      update_file_from_zip(new_file, content_file) do |txt|
+
+        replace_fields!(txt)
+        replace_tables!(txt)
+        replace_image_refs!(txt)
+        replace_sections!(txt)
+
+      end
+
+    end
+
+    unless @images.empty?
+      image_dir_name = "Pictures"
+      dir = File.join("#{@tmp_dir}", image_dir_name)
+      add_files_to_dir(@images.values, dir)
+      add_dir_to_zip(new_file, dir, image_dir_name)
+    end
+
+    new_file
+
+  end
+
+private
+
+  def replace_fields!(content)
+    hash_gsub!(content, @values)
+  end
+
+  def replace_tables!(content)
+
+    @tables.each do |table|
+      table.replace!(content)
+    end
+
+  end
+
+  def replace_sections!(content)
+
+    @sections.each do |section|
+      section.replace!(content)
+    end
+
+  end
+
+  def replace_image_refs!(content)
+    @images.each_pair do |image_name, path|
+      #Set the new image path
+      new_path = File.join("Pictures", File.basename(path))
+      #Search for the image
+      image_rgx = Regexp.new("draw:name=\"#{image_name}\".*?>")
+      content_match = content.match(image_rgx)
+      if content_match
+        replace_path = content_match[1]
+        content.gsub!(content_match[0], content_match[0].gsub(replace_path, new_path))
+      end
+    end
+  end
+
+end
+
+end
\ No newline at end of file
diff --git a/lib/odf-report/section.rb b/lib/odf-report/section.rb
new file mode 100644
index 0000000..8b250e5
--- /dev/null
+++ b/lib/odf-report/section.rb
@@ -0,0 +1,126 @@
+module ODFReport
+
+class Section
+  include HashGsub
+
+  attr_accessor :fields, :tables, :data, :name
+
+  def initialize(name)
+    @name = name
+
+    @fields = {}
+    @data = []
+    @tables = []
+  end
+
+  def add_field(name, field=nil, &block)
+    if field
+      @fields[name] = lambda { |item| item.send(field)}
+    else
+      @fields[name] = block
+    end
+  end
+
+  def add_table(table_name, collection_field, opts={}, &block)
+    opts.merge!(:name => table_name, :collection_field => collection_field)
+    tab = Table.new(opts)
+    yield(tab)
+    @tables << tab
+
+  end
+
+  def populate(collection)
+
+    collection.each do |item|
+      row = {}
+      @fields.each do |field_name, block1|
+        row[field_name] = block1.call(item)
+      end
+
+      row[:tables] = {}
+      @tables.each do |table|
+        collection = get_collection_from_item(item, table.collection_field)
+        row[:tables][table.name] = table.values(collection)
+      end
+
+      @data << row
+    end
+
+  end
+
+  def replace!(content)
+
+    # search for the table inside the content
+    section_rgx = Regexp.new("((.*?)<\/text:section>)", "m")
+    section_match = content.match(section_rgx)
+
+    if section_match
+      section_full = section_match[0]
+      section_content = section_match[2]
+
+      # extract the section from the content
+      content.gsub!(section_full, "[SECTION_#{@name}]")
+
+      new_content = ""
+
+      # for each record
+      @data.each do |_values|
+
+        # generates one new row (table-row), based in the model extracted
+        # from the original table
+        tmp_row = section_content.dup
+
+        # replace values in the section_content and stores in new_content
+        hash_gsub!(tmp_row, _values)
+
+        @tables.each do |t|
+          t.replace!(tmp_row, _values[:tables][t.name])
+        end
+
+        new_content << tmp_row
+      end
+
+      # replace back the table into content
+      content.gsub!("[SECTION_#{@name}]", new_content)
+
+    end # if table match
+
+  end # replace_section
+
+private
+
+  def get_collection_from_item(item, collection_field)
+
+    if collection_field.is_a?(Array)
+      tmp = item.dup
+      collection_field.each do |f|
+        if f.is_a?(Hash)
+          tmp = tmp.send(f.keys[0], f.values[0])
+        else
+          tmp = tmp.send(f)
+        end
+      end
+      collection = tmp
+    else
+      collection = item.send(collection_field)
+    end
+
+    return collection
+  end
+
+  def hash_gsub!(_text, hash_of_values)
+    hash_of_values.each do |key, val|
+      _text.gsub!("[#{key.to_s.upcase}]", html_escape(val))
+    end
+  end
+
+  HTML_ESCAPE = { '&' => '&',  '>' => '>',   '<' => '<', '"' => '"' }
+
+  def html_escape(s)
+    return "" unless s
+    s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
+  end
+
+end
+
+end
\ No newline at end of file
diff --git a/lib/odf-report/table.rb b/lib/odf-report/table.rb
new file mode 100644
index 0000000..248a4b4
--- /dev/null
+++ b/lib/odf-report/table.rb
@@ -0,0 +1,144 @@
+module ODFReport
+
+class Table
+  include HashGsub
+
+  attr_accessor :fields, :rows, :name, :collection_field, :data, :header
+
+  def initialize(opts)
+    @name             = opts[:name]
+    @collection_field = opts[:collection_field]
+    @collection       = opts[:collection]
+    @header           = opts[:header] || false
+
+    @fields = {}
+    @rows = []
+    @data = []
+  end
+
+  def add_column(name, field=nil, &block)
+    if field
+      @fields[name] = lambda { |item| item.send(field)}
+    elsif block_given?
+      @fields[name] = block
+    else
+      @fields[name] = lambda { |item| item.send(name)}
+    end
+  end
+
+  def values(collection)
+    ret = []
+    collection.each do |item|
+      row = {}
+      @fields.each do |field_name, block1|
+        row[field_name] = block1.call(item) || ''
+      end
+      ret << row
+    end
+    ret
+  end
+
+  def populate(collection)
+    @data = values(collection)
+  end
+
+  def replace!(content, rows = nil)
+    @data = rows if rows
+
+    # search for the table inside the content
+    table_rgx = Regexp.new("(.*?<\/table:table>)", "m")
+    table_match = content.match(table_rgx)
+
+    if table_match
+      table = table_match[0]
+
+      # extract the table from the content
+      content.gsub!(table, "[TABLE_#{@name}]")
+
+      # search for the table:row's
+      row_rgx = Regexp.new("()", "m")
+
+      # use scan (instead of match) as the table can have more than one table-row (header and data)
+      # and scan returns all matches
+      row_match = table.scan(row_rgx)
+
+      unless row_match.empty?
+
+        replace_rows!(table, row_match)
+
+        new_rows = ""
+
+        # for each record
+        @data.each do |_values|
+
+          # generates one new row (table-row), based in the model extracted
+          # from the original table
+          tmp_row = get_next_row.dup
+
+          # replace values in the model_row and stores in new_rows
+          hash_gsub!(tmp_row, _values)
+
+          new_rows << tmp_row
+        end
+
+        # replace back the lines into the table
+        table.gsub!("[ROW_#{@name}]", new_rows)
+
+      end # unless row_match.empty?
+
+      # replace back the table into content
+      if @data.empty?
+        content.gsub!("[TABLE_#{@name}]", "")
+      else
+        content.gsub!("[TABLE_#{@name}]", table)
+      end
+
+    end # if table match
+
+  end # replace
+
+private
+
+  def replace_rows!(table, rows)
+
+    rows.delete_at(0) if @header # ignore the header
+
+    @rows = rows.dup
+    @row_cursor = 0
+
+    # extract the rows from the table
+    first = rows.delete_at(0)[0]
+    table.gsub!(first, "[ROW_#{@name}]")
+
+    rows.each do |r|
+      table.gsub!(r[0], "")
+    end
+
+  end
+
+  def get_next_row
+    ret = @rows[@row_cursor]
+    if @rows.size == @row_cursor + 1
+      @row_cursor = 0
+    else
+      @row_cursor += 1
+    end
+    return ret[0]
+  end
+
+  def hash_gsub!(_text, hash_of_values)
+    hash_of_values.each do |key, val|
+      _text.gsub!("[#{key.to_s.upcase}]", html_escape(val))
+    end
+  end
+
+  HTML_ESCAPE = { '&' => '&',  '>' => '>',   '<' => '<', '"' => '"' }
+
+  def html_escape(s)
+    return "" unless s
+    s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
+  end
+
+end
+
+end
\ No newline at end of file
diff --git a/test/sections.odt b/test/sections.odt
new file mode 100644
index 0000000..1677dc9
Binary files /dev/null and b/test/sections.odt differ
diff --git a/test/test.odt b/test/test.odt
index c232f55..6070e4d 100644
Binary files a/test/test.odt and b/test/test.odt differ
diff --git a/test/test.rb b/test/test.rb
index ff5d6e4..c07a2f4 100644
--- a/test/test.rb
+++ b/test/test.rb
@@ -1,35 +1,36 @@
 require '../lib/odf-report'
+require 'ostruct'
 
 col1 = []
-col1 << {:name=>"name 01",  :id=>"01",  :address=>"this is address 01"}
-col1 << {:name=>"name 03",  :id=>"03",  :address=>"this is address 03"}
-col1 << {:name=>"name 02",  :id=>"02",  :address=>"this is address 02"}
-col1 << {:name=>"name 04",  :id=>"04",  :address=>"this is address 04"}
+(1..15).each do |i|
+  col1 << OpenStruct.new({:name=>"name #{i}",  :id=>i,  :address=>"this is address #{i}"})
+end
+
 
 col2 = []
-col2 << {:name=>"josh harnet",  :id=>"02",    :address=>"testing <&> ",                 :phone=>99025668, :zip=>"90420-002"}
-col2 << {:name=>"sandro",       :id=>"45",    :address=>"address with &",               :phone=>88774451, :zip=>"90490-002"}
-col2 << {:name=>"ellen bicca",  :id=>"77",    :address=>"
", :phone=>77025668, :zip=>"94420-002"} +col2 << OpenStruct.new({:name=>"josh harnet", :id=>"02", :address=>"testing <&> ", :phone=>99025668, :zip=>"90420-002"}) +col2 << OpenStruct.new({:name=>"sandro duarte", :id=>"45", :address=>"address with &", :phone=>88774451, :zip=>"90490-002"}) +col2 << OpenStruct.new({:name=>"ellen bicca", :id=>"77", :address=>"
", :phone=>77025668, :zip=>"94420-002"}) -report = ODFReport.new("test.odt") do |r| +report = ODFReport::Report.new("test.odt") do |r| - r.add_field("HEADER_FIELD", "This &field was in the HEADER") + r.add_field("HEADER_FIELD", "This field was in the HEADER") r.add_field("TAG_01", "New tag") r.add_field("TAG_02", "TAG-2 -> New tag") - r.add_table("TABLE_01", col1) do |row, item| - row["FIELD_01"] = item[:id] - row["FIELD_02"] = item[:name] - row["FIELD_03"] = item[:address] + r.add_table("TABLE_01", col1, :header=>true) do |t| + t.add_column(:field_01, :id) + t.add_column(:field_02, :name) + t.add_column(:field_03, :address) end - r.add_table("TABLE_02", col2) do |row, item| - row["FIELD_04"] = item[:id] - row["FIELD_05"] = item[:name] - row["FIELD_06"] = item[:address] - row["FIELD_07"] = item[:phone] - row["FIELD_08"] = item[:zip] + r.add_table("TABLE_02", col2) do |t| + t.add_column(:field_04, :id) + t.add_column(:field_05, :name) + t.add_column(:field_06, :address) + t.add_column(:field_07, :phone) + t.add_column(:field_08, :zip) end r.add_image("graphics1", File.join(Dir.pwd, 'piriapolis.jpg')) @@ -37,3 +38,40 @@ end report.generate("result.odt") + +class Item + attr_accessor :name, :sid, :children + def initialize(_name, _sid, _children=[]) + @name=_name + @sid=_sid + @children=_children + end +end + +items = [] +items << Item.new("Dexter Morgan", '007', %w(sawyer juliet hurley locke jack freckles)) +items << Item.new("Danny Crane", '302', %w(sidney sloane jack michael marshal)) +items << Item.new("Coach Taylor", '220', %w(meredith christina izzie alex george)) + +report = ODFReport::Report.new("sections.odt") do |r| + + r.add_field("TAG_01", "New tag") + r.add_field("TAG_02", "TAG-2 -> New tag") + + r.add_section("SECTION_01", items) do |s| + + s.add_field('NAME') do |i| + i.name + end + + s.add_field('SID', :sid) + + s.add_table('TABLE_S1', :children, :header=>true) do |t| + t.add_column('NAME1') { |item| "-> #{item}" } + t.add_column('INV') { |item| item.to_s.reverse.upcase } + end + end + +end + +report.generate("section_result.odt") \ No newline at end of file