Class: NewsFetcher::History

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

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file:, index_key: nil) ⇒ History

Returns a new instance of History.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/newsfetcher/history.rb', line 8

def initialize(file:, index_key: nil)
  @file = Path.new(file)
  @entries = []
  @index = {}
  @index_key = index_key
  if @file.exist?
    load_entries
  else
    @file.touch
  end
end

Instance Attribute Details

#entriesObject

Returns the value of attribute entries.



6
7
8
# File 'lib/newsfetcher/history.rb', line 6

def entries
  @entries
end

#fileObject

Returns the value of attribute file.



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

def file
  @file
end

Instance Method Details

#<<(entry) ⇒ Object



26
27
28
29
30
# File 'lib/newsfetcher/history.rb', line 26

def <<(entry)
  entry = Entry.new(**entry) if entry.kind_of?(Hash)
  add_entry(entry)
  @file.open('a') { |io| io.puts entry.to_json }
end

#[](key) ⇒ Object



32
33
34
35
# File 'lib/newsfetcher/history.rb', line 32

def [](key)
  raise "No index_key defined" unless @index_key
  @index[key]
end

#last_entryObject



41
42
43
# File 'lib/newsfetcher/history.rb', line 41

def last_entry
  @entries.last
end

#load_entriesObject



20
21
22
23
24
# File 'lib/newsfetcher/history.rb', line 20

def load_entries
  @file.readlines.map do |line|
    add_entry(Entry.from_json(line))
  end
end

#prune(before:) ⇒ Object



45
46
47
48
49
50
# File 'lib/newsfetcher/history.rb', line 45

def prune(before:)
  old = @entries.select { |e| e.time < before }
  old.each { |e| delete_entry(e) }
  save_entries
  old
end

#resetObject



52
53
54
55
56
# File 'lib/newsfetcher/history.rb', line 52

def reset
  @entries = []
  @index = {}
  @file.unlink
end

#sizeObject



37
38
39
# File 'lib/newsfetcher/history.rb', line 37

def size
  @entries.size
end