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 =
"\""
ROW_SEP =
"\r\n"
ARGS =
{:col_sep => COL_SEP, :quote_char => QUOTE_CHAR, :row_sep => ROW_SEP}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ WindowsCsv

Returns a new instance of WindowsCsv.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/windows_csv.rb', line 40

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



76
77
78
# File 'lib/windows_csv.rb', line 76

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

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



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/windows_csv.rb', line 11

def self.foreach(path, args = {})
  require "csv"
  
  File.open(path, "rb:bom|utf-16le") do |fp|
    csv_args = ARGS.clone
    csv_args.merge!(args[:csv_args]) if args[:csv_args]
    
    CSV.foreach(fp, csv_args) do |row|
      if csv_args[:headers]
        real = {}
      else
        real = []
      end
      
      row.each do |col|
        if csv_args[:headers]
          real[col[0].to_sym] = WindowsCsv.unescape(col[1])
        else
          real << WindowsCsv.unescape(col)
        end
      end
      
      yield real
    end
  end
  
  nil
end

.unescape(str) ⇒ Object



80
81
82
# File 'lib/windows_csv.rb', line 80

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

Instance Method Details

#<<(row) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/windows_csv.rb', line 58

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, ARGS).encode(Encoding::UTF_16LE)
  
  return nil
end