# frozen_string_literal: true module Crys class PagesDbManager PAGES_KEY = :pages PAGE = Struct.new( :filename, :source, :last_updated_at, :created_at, :in_rss, :in_all, keyword_init: true) def initialize(db_path:) @db_path = db_path end def add_page(page) @page = page hash = Digest::MD5.hexdigest(page.source) known_page = known_page(hash) upsert_db(hash, known_page) end def save save_db end def pages db.fetch(:pages).map do |_, data| PAGE.new(data) end end private attr_reader :hash, :page, :db_path def db @db ||= YAML.load_file( db_path, permitted_classes: [Time, Symbol] ) end def upsert_db(hash, known_page) record = PAGE.new(known_page || { filename: page.filename, source: page.source, created_at: Time.now, in_rss: true, in_all: true}) record.last_updated_at = page.last_updated_at @db[PAGES_KEY][hash] = record.to_h end def save_db File.write(db_path, db.to_yaml) end def known_page(hash) db[PAGES_KEY][hash] end end end