summaryrefslogtreecommitdiff
path: root/new/lib/crys/pages_db_manager.rb
blob: 6a5e71c9b0aada9bafc3e07a994f1732ef0d3222 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Crys
  class PagesDbManager
    PAGES_KEY = :pages
    PAGE = Struct.new(:filename, :file_path, :last_update, :in_rss, keyword_init: true) 

    def db_path
    end

    def add_page(processor)
      @processor = processor
      hash = Digest::MD5.hexdigest(processor.file_path)
      known_page = known_page(hash)

      upsert_db(hash, known_page)
      save_db
    end

    def pages
      db.fetch(:pages).map do | _, data|
        PAGE.new(data)
      end
    end

    private

    attr_reader :hash, :processor


    def db
      @db ||= YAML.load_file(
        db_path,
        permitted_classes: [Time, Symbol]
      )
    end

    def upsert_db(hash, known_page)
      if known_page
        record = PAGE.new(known_page)
      else
        record = PAGE.new(
          filename: processor.filename,
          file_path: processor.file_path,
          in_rss: true
        )
      end

      record.last_update = Time.now

      @db[PAGES_KEY][hash] = record.to_h
    end

    def save_db
      File.open(db_path, 'w') do |f|
        f.write db.to_yaml
      end
    end

    def known_page(hash)
      db[PAGES_KEY][hash]
    end
  end
end