Class: RelatonOasis::Index
- Inherits:
-
Object
- Object
- RelatonOasis::Index
- Defined in:
- lib/relaton_oasis/index.rb
Overview
Index of OASIS documents.
Class Method Summary collapse
-
.create_or_fetch ⇒ RelatonOasis::Index?
Read index from file or fetch from GitHub.
Instance Method Summary collapse
-
#[](id) ⇒ Hash
Fetch document’s record from index.
-
#[]=(doc, file) ⇒ Object
Put document’s record to index.
-
#initialize(file = "index.yaml") ⇒ Index
constructor
Initialize a new Index.
-
#read ⇒ Object
Read from file or create empty index.
-
#save ⇒ Object
Save index to file.
Constructor Details
#initialize(file = "index.yaml") ⇒ Index
Initialize a new Index
7 8 9 10 |
# File 'lib/relaton_oasis/index.rb', line 7 def initialize(file = "index.yaml") @file = file read end |
Class Method Details
.create_or_fetch ⇒ RelatonOasis::Index?
Read index from file or fetch from GitHub.
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/relaton_oasis/index.rb', line 17 def self.create_or_fetch file = File.join Dir.home, ".relaton", "oasis", "index.yaml" unless File.exist?(file) && File.ctime(file) > Time.now - 86_400 url = "https://raw.githubusercontent.com/relaton/relaton-data-oasis/main/index.yaml" idx = Net::HTTP.get URI url File.write file, idx, encoding: "UTF-8" end new file rescue StandardError => e Util.error "Failed to fetch index: #{e.}" end |
Instance Method Details
#[](id) ⇒ Hash
Fetch document’s record from index.
52 53 54 |
# File 'lib/relaton_oasis/index.rb', line 52 def [](id) @index.detect { |i| i[:id] == id } end |
#[]=(doc, file) ⇒ Object
Put document’s record to index.
35 36 37 38 39 40 41 42 43 |
# File 'lib/relaton_oasis/index.rb', line 35 def []=(doc, file) # rubocop:disable Metrics/AbcSize rec = self[doc.docidentifier[0].id] rec ||= begin @index << { id: doc.docidentifier[0].id } @index.last end rec[:title] = doc.title[0].title.content rec[:file] = file end |
#read ⇒ Object
Read from file or create empty index.
71 72 73 74 75 76 77 78 |
# File 'lib/relaton_oasis/index.rb', line 71 def read @index = if File.exist?(@file) YAML.load_file(@file, symbolize_names: true) else [] end end |
#save ⇒ Object
Save index to file.
59 60 61 62 63 64 65 66 |
# File 'lib/relaton_oasis/index.rb', line 59 def save File.open @file, "w:UTF-8" do |f| f.puts "---\n" @index.each do |i| f.puts "- id: '#{i[:id]}'\n title: '#{i[:title]}'\n file: '#{i[:file]}'\n" end end end |