Class: Glossarist::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/glossarist/collection.rb

Overview

TODO:

Add support for lazy concept loading.

TODO:

Consider extracting persistence backend to a separate class.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path: nil) ⇒ Collection

Returns a new instance of Collection.

Parameters:

  • path (String) (defaults to: nil)

    concepts directory path, either absolute or relative to CWD



18
19
20
21
# File 'lib/glossarist/collection.rb', line 18

def initialize(path: nil)
  @path = path
  @index = {}
end

Instance Attribute Details

#pathString

Path to concepts directory.

Returns:

  • (String)


14
15
16
# File 'lib/glossarist/collection.rb', line 14

def path
  @path
end

Instance Method Details

#each(&block) ⇒ Object



23
24
25
# File 'lib/glossarist/collection.rb', line 23

def each(&block)
  @index.each_value(&block)
end

#fetch(id) ⇒ Concept? Also known as: []

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

Parameters:

  • id (String)

    Concept ID

Returns:



33
34
35
# File 'lib/glossarist/collection.rb', line 33

def fetch(id)
  @index[id]
end

#fetch_or_initialize(id) ⇒ Concept

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.

Parameters:

  • id (String)

    Concept ID

Returns:



46
47
48
# File 'lib/glossarist/collection.rb', line 46

def fetch_or_initialize(id)
  fetch(id) or store(Concept.new(id: id))
end

#load_conceptsObject

Reads all concepts from files.



62
63
64
65
66
# 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_conceptsObject

Writes all concepts to files.



73
74
75
# File 'lib/glossarist/collection.rb', line 73

def save_concepts
  @index.each_value &method(:save_concept_to_file)
end

#store(concept) ⇒ Object Also known as: <<

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

Parameters:

  • concept (Concept)

    concept about to be added



55
56
57
# File 'lib/glossarist/collection.rb', line 55

def store(concept)
  @index[concept.id] = concept
end