Class: CLI

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stdin = STDIN, stdout = STDOUT, path_to_histfile = 'history.txt') ⇒ CLI

Returns a new instance of CLI.



7
8
9
10
11
# File 'lib/cli.rb', line 7

def initialize(stdin = STDIN, stdout = STDOUT, path_to_histfile='history.txt')
  @stdin = stdin
  @stdout = stdout
  @inspector ||= Inspector.new(read_and_encode(path_to_histfile))
end

Instance Attribute Details

#inspectorObject (readonly)

Returns the value of attribute inspector.



5
6
7
# File 'lib/cli.rb', line 5

def inspector
  @inspector
end

#stdinObject (readonly)

Returns the value of attribute stdin.



5
6
7
# File 'lib/cli.rb', line 5

def stdin
  @stdin
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



5
6
7
# File 'lib/cli.rb', line 5

def stdout
  @stdout
end

Instance Method Details

#ascii_chart(stats) ⇒ Object



20
21
22
# File 'lib/cli.rb', line 20

def ascii_chart(stats)
  AsciiCharts::Cartesian.new(stats).draw
end

#bar_graph(stats) ⇒ Object



24
25
26
27
28
# File 'lib/cli.rb', line 24

def bar_graph(stats)
  out_of_100(stats).reduce("") do |memo, (command, occurences)|
    memo += "#{'#'*occurences} #{occurences.to_s}% -- #{command.to_s}\n"
  end
end

#format_results(results) ⇒ Object



39
40
41
# File 'lib/cli.rb', line 39

def format_results(results)
  results.map { |command, count| "#{count} #{command}" }
end

#get_inputObject



43
44
45
# File 'lib/cli.rb', line 43

def get_input
  command = stdin.gets.chomp
end

#out_of_100(stats) ⇒ Object



30
31
32
33
# File 'lib/cli.rb', line 30

def out_of_100(stats)
  total = stats.reduce(0) {|memo, (command, occurences)| memo += occurences}
  stats.map { |command, occurences| [command, occurences = (occurences.to_f/total.to_f*100).round] }
end


13
14
15
16
17
18
# File 'lib/cli.rb', line 13

def print_top_ten
  stats = inspector.top_ten
  stdout.puts format_results(stats)
  stdout.puts ascii_chart(stats)
  stdout.puts bar_graph(stats)
end

#read_and_encode(history) ⇒ Object



47
48
49
# File 'lib/cli.rb', line 47

def read_and_encode(history)
  File.read(history).encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
end

#show_count_for_commandObject



35
36
37
# File 'lib/cli.rb', line 35

def show_count_for_command
  stdout.puts(inspector.count(get_input))
end