Class: Glossarist::Collection
- Inherits:
-
Object
- Object
- Glossarist::Collection
- Includes:
- Enumerable
- Defined in:
- lib/glossarist/collection.rb
Overview
Add support for lazy concept loading.
Consider extracting persistence backend to a separate class.
Instance Attribute Summary collapse
-
#path ⇒ String
Path to concepts directory.
Instance Method Summary collapse
- #each(&block) ⇒ Object
-
#fetch(id) ⇒ Concept?
(also: #[])
Returns concept with given ID, if it is present in collection, or
nil
otherwise. -
#fetch_or_initialize(id) ⇒ Concept
If concept with given ID is present in this collection, returns that concept.
-
#initialize(path: nil) ⇒ Collection
constructor
A new instance of Collection.
-
#load_concepts ⇒ Object
Reads all concepts from files.
-
#save_concepts ⇒ Object
Writes all concepts to files.
-
#store(concept) ⇒ Object
(also: #<<)
Adds concept to the collection.
Constructor Details
#initialize(path: nil) ⇒ Collection
Returns a new instance of Collection.
18 19 20 21 |
# File 'lib/glossarist/collection.rb', line 18 def initialize(path: nil) @path = path @index = {} end |
Instance Attribute Details
#path ⇒ String
Path to concepts directory.
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.
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.
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_concepts ⇒ Object
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_concepts ⇒ Object
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.
55 56 57 |
# File 'lib/glossarist/collection.rb', line 55 def store(concept) @index[concept.id] = concept end |