class Glossarist::Collection

@todo Add support for lazy concept loading. @todo Consider extracting persistence backend to a separate class.

Attributes

path[RW]

Path to concepts directory. @return [String]

Public Class Methods

new(path: nil) click to toggle source

@param path [String]

concepts directory path, either absolute or relative to CWD
# File lib/glossarist/collection.rb, line 18
def initialize(path: nil)
  @path = path
  @index = {}
end

Public Instance Methods

<<(concept)
Alias for: store
[](id)
Alias for: fetch
each(&block) click to toggle source
# File lib/glossarist/collection.rb, line 23
def each(&block)
  @index.each_value(&block)
end
fetch(id) click to toggle source

Returns concept with given ID, if it is present in collection, or nil otherwise.

@param id [String]

Concept ID

@return [Concept, nil]

# File lib/glossarist/collection.rb, line 33
def fetch(id)
  @index[id]
end
Also aliased as: []
fetch_or_initialize(id) click to toggle source

If concept with given ID is present in this collection, returns that concept. Otherwise, instantiates a new concept, adds it to the collection, and returns it.

@param id [String]

Concept ID

@return [Concept]

# File lib/glossarist/collection.rb, line 46
def fetch_or_initialize(id)
  fetch(id) or store(Concept.new(id: id))
end
load_concepts() click to toggle source

Reads all concepts from files.

# File lib/glossarist/collection.rb, line 62
def load_concepts
  Dir.glob(concepts_glob) do |filename|
    store(load_concept_from_file(filename))
  end
end
save_concepts() click to toggle source

Writes all concepts to files.

# File lib/glossarist/collection.rb, line 73
def save_concepts
  @index.each_value &method(:save_concept_to_file)
end
store(concept) click to toggle source

Adds concept to the collection. If collection contains a concept with the same ID already, that concept is replaced.

@param concept [Concept]

concept about to be added
# File lib/glossarist/collection.rb, line 55
def store(concept)
  @index[concept.id] = concept
end
Also aliased as: <<

Private Instance Methods

concepts_glob() click to toggle source
# File lib/glossarist/collection.rb, line 82
        def concepts_glob
  File.join(path, "concept-*.{yaml,yml}")
end
load_concept_from_file(filename) click to toggle source
# File lib/glossarist/collection.rb, line 68
        def load_concept_from_file(filename)
  Concept.from_h(Psych.safe_load(File.read(filename)))
end
save_concept_to_file(concept) click to toggle source
# File lib/glossarist/collection.rb, line 77
        def save_concept_to_file(concept)
  filename = File.join(path, "concept-#{concept.id}.yaml")
  File.write(filename, Psych.dump(concept.to_h))
end