Class: Coolline::History

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

Overview

Class used to keep track of input. It keeps a certain amount of lines at most in memory, and stores them in a file.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, max_size = 5000) ⇒ History

Returns a new instance of History.



7
8
9
10
11
12
13
14
15
16
# File 'lib/coolline/history.rb', line 7

def initialize(filename, max_size = 5000)
  @io       = open_file(filename)
  @max_size = max_size

  @lines = []

  load_lines
  delete_empty
  @index = size
end

Instance Attribute Details

#indexObject

Returns the value of attribute index.



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

def index
  @index
end

#max_sizeObject

Returns the value of attribute max_size.



72
73
74
# File 'lib/coolline/history.rb', line 72

def max_size
  @max_size
end

Instance Method Details

#<<(el) ⇒ Object



44
45
46
47
48
49
# File 'lib/coolline/history.rb', line 44

def <<(el)
  @lines << el.dup
  @lines.delete_at(0) if @lines.size > @max_size

  self
end

#[](id) ⇒ Object



55
56
57
# File 'lib/coolline/history.rb', line 55

def [](id)
  @lines[id]
end

#[]=(id, val) ⇒ Object



59
60
61
# File 'lib/coolline/history.rb', line 59

def []=(id, val)
  @lines[id] = val.dup
end

#closeObject



25
26
27
28
# File 'lib/coolline/history.rb', line 25

def close
  @io.close
  @lines.clear
end

#currentObject



51
52
53
# File 'lib/coolline/history.rb', line 51

def current
  self[@index]
end

#delete_emptyObject



40
41
42
# File 'lib/coolline/history.rb', line 40

def delete_empty
  @lines.reject!(&:empty?)
end

#reopen(filename) ⇒ Object



18
19
20
21
22
23
# File 'lib/coolline/history.rb', line 18

def reopen(filename)
  close
  @io = open_file(filename)

  load_lines
end

#save_lineObject



63
64
65
66
# File 'lib/coolline/history.rb', line 63

def save_line
  @io.puts self[-1]
  @io.flush
end

#search(pattern, first_line = -1)) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/coolline/history.rb', line 30

def search(pattern, first_line = -1)
  return to_enum(:search, pattern, first_line) unless block_given?
  return if size == 0

  first_line %= size
  @lines[0..first_line].reverse_each.with_index do |line, i|
    yield line, first_line - i if pattern === line
  end
end

#sizeObject



68
69
70
# File 'lib/coolline/history.rb', line 68

def size
  @lines.size
end