Module: Run

Extended by:
Run
Included in:
Run
Defined in:
lib/run.rb,
lib/run/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#byeObject



127
128
129
130
# File 'lib/run.rb', line 127

def bye
  puts "\nBye"
  exit
end

#helpObject



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/run.rb', line 48

def help
  puts <<~eof
  Usage: run

  Options:
    -h: show this message
    -s: print stats
    -l: message length [1: short, 2: medium, 3: long]
    -q: print quotes.yml path
  eof
  exit
end

#parse_options(args) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/run.rb', line 61

def parse_options(args)
  if args.first=='-s'
    stats
  end

  if args.first=='-q'
    puts quotes_file
    exit
  end

  if args.shift=='-l' and args.first.to_i > 0
    @max_length=args.first.to_i
    return
  end

  puts "Unknown option"
  bye
rescue => e
  "Bad options. For help: `run -h`"
end

#posObject



123
124
125
# File 'lib/run.rb', line 123

def pos
  @pos
end


106
107
108
# File 'lib/run.rb', line 106

def print_text
  print "\r"+text.sub(/(.{#{pos}})/,"#{@color}\\1#{@no_color}")
end

#quotesObject



94
95
96
97
98
99
100
# File 'lib/run.rb', line 94

def quotes
  YAML.load(open(quotes_file))
      .sort_by(&:length)
      .select {|e| e.size<@max_length}
rescue => e
  "Error while reading #{quotes_file}"
end

#quotes_fileObject



102
103
104
# File 'lib/run.rb', line 102

def quotes_file
  "#{__dir__}/run/quotes.yml"
end

#race(args) ⇒ Object



10
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
39
40
41
42
43
44
45
46
# File 'lib/run.rb', line 10

def race(args)
  help if !(args & %w[-h --help]).empty?

  parse_options(args) unless args.empty?

  trap('INT') { bye }
  trap('TERM') { bye }

  @eof=0x04
  @max_length||=4000

  if quotes.empty?
    puts "No quotes with less than #{@max_length} characters found"
    exit
  end

  @text=quotes[rand(quotes.size)]

  @color="\e[4;32m"
  @no_color="\e[m"

  @pos=0
  max_pos=text.size

  # average English word length
  @word_length=5

  @start_time=time
  print_text

  loop do
    update_text
    break if pos==max_pos
  end

  puts "\nWPM: #{wpm}"
end

#statsObject



82
83
84
# File 'lib/run.rb', line 82

def stats
  bye
end

#textObject



119
120
121
# File 'lib/run.rb', line 119

def text
  @text
end

#timeObject



86
87
88
# File 'lib/run.rb', line 86

def time
  Time.now.to_i
end

#update_textObject



110
111
112
113
114
115
116
117
# File 'lib/run.rb', line 110

def update_text
  system('stty raw -echo')
  bye if (c=STDIN.getc)==@eof.chr
  @pos+=1 if c==text[pos]
ensure
  system('stty -raw echo')
  print_text
end

#wpmObject



90
91
92
# File 'lib/run.rb', line 90

def wpm
  text.size*60/((time-@start_time)*@word_length)
end