lib/rspreadsheet/workbook.rb in rspreadsheet-0.2.3 vs lib/rspreadsheet/workbook.rb in rspreadsheet-0.2.4

- old
+ new

@@ -1,14 +1,14 @@ require 'zip' require 'libxml' module Rspreadsheet class Workbook - attr_reader :worksheets, :filename + attr_reader :filename attr_reader :xmlnode # debug def initialize(afilename=nil) - @worksheets={} + @worksheets=[] @filename = afilename @content_xml = Zip::File.open(@filename || './lib/rspreadsheet/empty_file_template.ods') do |zip| LibXML::XML::Document.io zip.get_input_stream('content.xml') end @xmlnode = @content_xml.find_first('//office:spreadsheet') @@ -28,36 +28,48 @@ zip.get_output_stream('content.xml') do |f| f.write @content_xml.to_s(:indent => false) end end end + def xmldoc; @xmlnode.doc end + + #@!group Worskheets methods def create_worksheet_from_node(source_node) sheet = Worksheet.new(source_node) register_worksheet(sheet) return sheet end - def create_worksheet_with_name(name) + def create_worksheet(name = "Strana #{worksheets_count}") sheet = Worksheet.new(name) register_worksheet(sheet) return sheet end - def create_worksheet - index = worksheets_count - create_worksheet_with_name("Strana #{index}") + # @return [Integer] number of sheets in the workbook + def worksheets_count; @worksheets.length end + # @return [String] names of sheets in the workbook + def worksheet_names; @worksheets.collect{ |ws| ws.name } end + # @param [Integer,String] + # @return [Worskheet] worksheet with given index or name + def worksheets(index_or_name) + case index_or_name + when Integer then begin + case index_or_name + when 0 then nil + when 1..Float::INFINITY then @worksheets[index_or_name-1] + when -Float::INFINITY..-1 then @worksheets[index_or_name] # zaporne indexy znamenaji pocitani zezadu + end + end + when String then @worksheets.select{|ws| ws.name == index_or_name}.first + when NilClass then nil + else raise 'method worksheets requires Integer index of the sheet or its String name' + end end + def [](index_or_name); self.worksheets(index_or_name) end + + private def register_worksheet(worksheet) index = worksheets_count+1 - @worksheets[index]=worksheet - @worksheets[worksheet.name]=worksheet unless worksheet.name.nil? + @worksheets[index-1]=worksheet @xmlnode << worksheet.xmlnode if worksheet.xmlnode.doc != @xmlnode.doc - end - def worksheets_count - @worksheets.keys.select{ |k| k.kind_of? Numeric }.size #TODO: ?? max - end - def worksheet_names - @worksheets.keys.reject{ |k| k.kind_of? Numeric } - end - def xmldoc - @xmlnode.doc end end end