Module: LTSV

Extended by:
LTSV
Included in:
LTSV
Defined in:
lib/gri/ltsv.rb

Overview

conding: us-ascii

Instance Method Summary collapse

Instance Method Details

#dump_to_file(values, path) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/gri/ltsv.rb', line 29

def dump_to_file values, path
  tmp_path = path + ".tmp#{$$}"
  open(tmp_path, 'w') {|f|
    dump_to_io values, f
  }
  File.rename tmp_path, path
end

#dump_to_io(values, io) ⇒ Object



22
23
24
25
26
27
# File 'lib/gri/ltsv.rb', line 22

def dump_to_io values, io
  (Hash === values) and values = values.values
  for value in values
    io.puts serialize(value)
  end
end

#escape18(s) ⇒ Object



4
5
6
# File 'lib/gri/ltsv.rb', line 4

def escape18 s
  s.to_s.gsub(/\n/, "\\n").gsub(/\r/, "\\r").gsub(/\t/, "\\t")
end

#escape19(s) ⇒ Object



8
9
10
11
# File 'lib/gri/ltsv.rb', line 8

def escape19 s
  s.to_s.force_encoding(Encoding::ASCII_8BIT).
    gsub(/\n/, "\\n").gsub(/\r/, "\\r").gsub(/\t/, "\\t")
end

#load_from_file(path) ⇒ Object



51
52
53
# File 'lib/gri/ltsv.rb', line 51

def load_from_file path
  File.open(path, 'rb') {|f| parse_io f}
end

#parse_io(io) ⇒ Object



55
56
57
# File 'lib/gri/ltsv.rb', line 55

def parse_io io
  io.map {|line| parse_string line.chomp}
end

#parse_string(line) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/gri/ltsv.rb', line 37

def parse_string line
  h = {}
  for item in line.split("\t")
    k, v = item.split(':', 2)
    next unless k
    h[k] = case v
           when nil; nil
           when ''; nil
           else v
           end
  end
  h
end

#serialize(value) ⇒ Object



17
18
19
20
# File 'lib/gri/ltsv.rb', line 17

def serialize value
  h = value.to_hash
  h.map {|k, v| "#{k}:#{escape v}"}.join("\t")
end