Class: Jets::CLI::Exec::Repl::History

Inherits:
Object
  • Object
show all
Defined in:
lib/jets/cli/exec/repl/history.rb

Constant Summary collapse

MAX_SIZE =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ History

Returns a new instance of History.



6
7
8
9
10
# File 'lib/jets/cli/exec/repl/history.rb', line 6

def initialize(options = {})
  @options = options
  @file = "#{ENV["HOME"]}/.jets/history"
  @list = load
end

Instance Attribute Details

#listObject (readonly)

Returns the value of attribute list.



5
6
7
# File 'lib/jets/cli/exec/repl/history.rb', line 5

def list
  @list
end

Instance Method Details

#add(cmd) ⇒ Object



12
13
14
15
# File 'lib/jets/cli/exec/repl/history.rb', line 12

def add(cmd)
  @list << cmd
  @list.shift if @list.size > MAX_SIZE
end

#display(num = nil) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/jets/cli/exec/repl/history.rb', line 17

def display(num = nil)
  num ||= 20
  num = (num == "all") ? @list.length : num.to_i
  num = [@list.length, num].min
  start_index = [@list.length - num, 0].max
  @list[start_index..].each_with_index { |cmd, index| puts "#{start_index + index + 1}: #{cmd}" }
end

#loadObject



25
26
27
28
29
30
31
32
33
# File 'lib/jets/cli/exec/repl/history.rb', line 25

def load
  history = if File.exist?(@file)
    File.readlines(@file).map(&:chomp)
  else
    []
  end
  history.each { |cmd| Readline::HISTORY << cmd }
  history
end

#saveObject



35
36
37
38
39
40
# File 'lib/jets/cli/exec/repl/history.rb', line 35

def save
  FileUtils.mkdir_p(File.dirname(@file))
  File.open(@file, "w") do |file|
    @list.each { |cmd| file.puts cmd }
  end
end