Class: ExtCsvExporter

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

Constant Summary collapse

DEFAULT_FILENAME =
"measurement.txt"

Instance Method Summary collapse

Constructor Details

#initialize(data_type, data_content) ⇒ ExtCsvExporter

See to_string for allowed data types. data_content accepts the output from ExtCsv.to_ary.



715
716
717
718
719
# File 'lib/extcsv.rb', line 715

def initialize(data_type, data_content)
  @line_sep  = "\n"
  @data_type = data_type
  @content   = data_content
end

Instance Method Details

#to_file(file, filetype = nil) ⇒ Object

Create files of types, that are allowed by ExtCsvExporter.to_string



774
775
776
777
778
779
780
781
782
783
784
# File 'lib/extcsv.rb', line 774

def to_file(file, filetype=nil)
  # Create the output directory
  dir      = File.dirname(File.expand_path(file))
  FileUtils.mkdir_p(dir) unless File.directory?(dir)

  filename = File.directory?(file) ? DEFAULT_FILENAME : File.basename(file)
  filetype = File.extname(filename)[1..-1] if filetype.nil? or filetype.empty?
  File.open(file,"w") {|f|
    f << to_string(filetype)
  }
end

#to_string(string_type, enc = "en") ⇒ Object

Optional string types are:

  • csv , separation by ‘,’

  • ssv, separation by ‘;’

  • tsv, separation by ‘t’

  • psv, separation by ‘|’

  • xml, see to_xml



727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/extcsv.rb', line 727

def to_string(string_type,enc="en")
  string_type = "xml" if string_type.nil? or string_type.empty?
  out = ''
  case string_type
  when "csv"
    sep = ","
  when "ssv"
    sep = ";"
  when "tsv" , "txt"
    sep = "\t"
  when "psv"
    sep = "|"
  when "bsv"
    sep = " "
  when "xml" 
    out = to_xml
  when "tex"
  else
    puts "Wrong type! Use xml, tex, csv, ssv, psv, txt or tsv instead."
    raise
  end
  @content.transpose.each {|data_set|
    out << data_set.join(sep) + @line_sep
  } unless string_type == "xml"
  #out.gsub(/\./,",") if enc == "de"
  out
end

#to_xmlObject

XML-Documents must be treated separately: tags are named like the attributes.



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
# File 'lib/extcsv.rb', line 756

def to_xml
  xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"
  xml << "<" + @data_type + ">\n"
  output_array = @content.transpose
  tags         = output_array.first
  data         = output_array[1..-1]
  data.each {|values|
    xml << "  <record>\n"
    values.each_with_index {|value,i| 
      xml << "    <#{tags[i]}>#{value}</#{tags[i]}>\n"
    }
    xml << "  </record>\n"
  }
  xml << "</" + @data_type + ">"
  xml
end