Class: WindowsCsv

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

Overview

This class was heavily inspired by the great Dipth! github.com/dipth

Constant Summary collapse

ENCODING =
Encoding::UTF_8
BOM =

Byte Order Mark

"\377\376".force_encoding(Encoding::UTF_16LE)
COL_SEP =
"\t"
QUOTE_CHAR =
"\""

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ WindowsCsv

Returns a new instance of WindowsCsv.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/windows_csv.rb', line 30

def initialize(args)
  require "csv"
  
  @args = args
  
  if @args[:path]
    fp = File.open(@args[:path], "w", :encoding => ENCODING)
    @args[:io] = fp
  end
  
  begin
    @args[:io].write(BOM)
    yield self
  ensure
    fp.close if fp
  end
end

Class Method Details

.escape(str) ⇒ Object



66
67
68
# File 'lib/windows_csv.rb', line 66

def self.escape(str)
  return str.to_s.gsub("\n", "\\r\\n")
end

.foreach(path, args = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/windows_csv.rb', line 9

def self.foreach(path, args = {})
  require "rubygems"
  require "csv_lazy"
  
  File.open(path, "rb:bom|utf-16le") do |fp|
    csv_args = {:debug => false, :io => fp, :col_sep => COL_SEP, :quote_char => QUOTE_CHAR}
    csv_args.merge!(args[:csv_args]) if args[:csv_args]
    
    Csv_lazy.new(csv_args) do |row|
      real = []
      row.each do |col|
        real << col
      end
      
      yield row
    end
  end
  
  nil
end

Instance Method Details

#<<(row) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/windows_csv.rb', line 48

def <<(row)
  encoded = []
  
  row.each do |col|
    if col.is_a?(Time) or col.is_a?(DateTime)
      encoded << col.strftime("%Y-%m-%d %H:%M")
    elsif col.is_a?(Date)
      encoded << col.strftime("%Y-%m-%d")
    else
      encoded << WindowsCsv.escape(col)
    end
  end
  
  @args[:io].puts CSV.generate_line(encoded, :col_sep => COL_SEP, :quote_char => QUOTE_CHAR).encode(Encoding::UTF_16LE)
  
  return nil
end