Sha256: b7c1bb66301ecb28abbe822eebfcc1b12936cc365be4fc59e5ca68b282715122

Contents?: true

Size: 1.16 KB

Versions: 2

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

module Glossarist
  class ConceptManager
    # Path to concepts directory.
    # @return [String]
    attr_accessor :path

    # @param path [String]
    #   concepts directory path, either absolute or relative to CWD
    def initialize(path: nil)
      @path = path
    end

    # Reads all concepts from files.
    def load_from_files(collection: nil)
      collection ||= ManagedConceptCollection.new

      Dir.glob(concepts_glob) do |filename|
        collection.store(load_concept_from_file(filename))
      end
    end

    # Writes all concepts to files.
    def save_to_files(managed_concepts)
      managed_concepts.each_value &method(:save_concept_to_file)
    end

    def load_concept_from_file(filename)
      ManagedConcept.new(Psych.safe_load(File.read(filename)))
    rescue Psych::SyntaxError => e
      raise Glossarist::ParseError.new(filename: filename, line: e.line)
    end

    def save_concept_to_file(concept)
      filename = File.join(path, "concept-#{concept.id}.yaml")
      File.write(filename, Psych.dump(concept.to_h))
    end

    private

    def concepts_glob
      File.join(path, "concept-*.{yaml,yml}")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
glossarist-1.1.0 lib/glossarist/concept_manager.rb
glossarist-1.0.9 lib/glossarist/concept_manager.rb