Class: Kor::Input::Ltsv

Inherits:
Object
  • Object
show all
Defined in:
lib/kor/input/ltsv.rb,
lib/kor/input/ltsv/version.rb

Constant Summary collapse

DEFAULT_GUESS_TIME =
5
VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Ltsv

Returns a new instance of Ltsv.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/kor/input/ltsv.rb', line 9

def initialize(io)
  @io = io
  @keys = []
  @prekeys = nil
  @ltsvs = []
  @guess = true
  @guess_time = DEFAULT_GUESS_TIME
  @count = 0
  @fiber = Fiber.new do
    @ltsvs.each do |ltsv|
      Fiber.yield @keys.map{ |k| ltsv[k] }
    end
    # gets should be return nil when last
    Fiber.yield nil
  end
end

Instance Method Details

#getsObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/kor/input/ltsv.rb', line 52

def gets
  if @prekeys
    if line = @io.gets
      line.strip!
      ltsv = parse_line(line)
      @keys.map { |k| ltsv[k] }
    else
      nil
    end
  elsif 0 < @guess_time
    if @count < @guess_time
      @count += 1
      return resume
    end
    if line = @io.gets
      line.strip!
      ltsv = parse_line(line)
      @keys.map { |k| ltsv[k] }
    end
  else
    resume
  end
end

#headObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/kor/input/ltsv.rb', line 35

def head
  if @prekeys
    @keys = @prekeys.split(",")
  else
    while line = @io.gets
      line.strip!
      @ltsvs << parse_line(line)
      if 0 < @guess_time && @guess_time <= @ltsvs.length
        break
      end
    end
    @keys = @ltsvs.map { |ltsv| ltsv.keys }
    @keys.flatten!.uniq!
  end
  @keys
end

#parse(opt) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/kor/input/ltsv.rb', line 26

def parse(opt)
  opt.on("--key=KEY", "define keys preset (e.g. foo,bar,baz) (default auto)") do |arg|
    @prekeys = arg
  end
  opt.on("--guess-time=NUM", "load lines this time for guess. no guess if under 0 (default #{DEFAULT_GUESS_TIME})") do |arg|
    @guess_time = arg.to_i
  end
end

#parse_line(line) ⇒ Object



76
77
78
# File 'lib/kor/input/ltsv.rb', line 76

def parse_line(line)
  LTSV.parse(line, symbolize_keys: false).first
end

#resumeObject



80
81
82
83
84
# File 'lib/kor/input/ltsv.rb', line 80

def resume
  @fiber.resume
rescue FiberError
  nil
end