Class: Intar::Prompt

Inherits:
Object show all
Defined in:
lib/intar/prompt.rb

Instance Method Summary collapse

Constructor Details

#initialize(histfile: nil, limit: nil) ⇒ Prompt

Returns a new instance of Prompt.



13
14
15
16
17
# File 'lib/intar/prompt.rb', line 13

def initialize histfile: nil, limit: nil
  @limit = limit.nonzero?
  Readline::HISTORY.clear
  @new = 0
end

Instance Method Details

#ask(prompt) ⇒ Object



19
20
21
22
23
24
# File 'lib/intar/prompt.rb', line 19

def ask prompt
  l = Readline.readline prompt
rescue Interrupt
  puts "^C  --  #{$!.inspect}"
  retry
end

#lastObject



26
27
28
# File 'lib/intar/prompt.rb', line 26

def last
  Readline::HISTORY[-1] unless Readline::HISTORY.empty?
end

#limit_history(max) ⇒ Object



87
88
89
90
91
92
# File 'lib/intar/prompt.rb', line 87

def limit_history max
  n = Readline::HISTORY.length - max
  n.times { Readline::HISTORY.shift }
  @new > max and @new = max
  nil
end

#load_history(filepath) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/intar/prompt.rb', line 46

def load_history filepath
  with_filepath filepath do |p|
    read_file_if p do |f|
      h = []
      @new.times { h.push Readline::HISTORY.pop }
      Readline::HISTORY.clear
      f.each_line { |l|
        l.chomp!
        l.sub! "\r", "\n"
        Readline::HISTORY.push l
      }
      Readline::HISTORY.push h.pop while h.any?
    end
    nil
  end
end

#push(item) ⇒ Object



39
40
41
42
43
44
# File 'lib/intar/prompt.rb', line 39

def push item
  item.empty? and return
  last != item or return
  Readline::HISTORY.push item
  @new += 1
end

#save_history(filepath, maxsize) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/intar/prompt.rb', line 63

def save_history filepath, maxsize
  with_filepath filepath do |p|
    lock_histfile p do
      old, m = [], maxsize-@new
      read_file_if p do |f|
        f.each_line { |l|
          old.size >= m and old.shift
          old.push l
        }
      end
      File.open p, "w" do |f|
        old.each { |l| f.puts l }
        i = Readline::HISTORY.length - @new
        while i < Readline::HISTORY.length do
          l = Readline::HISTORY[ i].sub "\n", "\r"
          f.puts l
          i += 1
        end
      end
    end
    nil
  end
end

#scan_historyObject



30
31
32
33
34
35
36
37
# File 'lib/intar/prompt.rb', line 30

def scan_history
  i = Readline::HISTORY.length
  while i > 0 do
    i -= 1
    l = Readline::HISTORY[i]
    yield l
  end
end