Sha256: 1fc1d88b8decb14475184d73b273f38ad4e3770c144194b5c20bba2eff18b129

Contents?: true

Size: 1.39 KB

Versions: 7

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

require 'ostruct'
require 'pathname'

module Quby
  module Answers
    module Repos
      class DiskRepo < Base
        class Record < OpenStruct
        end

        attr_reader :path

        def initialize(path)
          @path = Pathname.new(path).expand_path
        end

        private

        def all_records(questionnaire_key)
          storage.map    { |filename| load_file(filename) }
                 .select { |record| record.questionnaire_key == questionnaire_key }
        end

        def find_record(id)
          load_file(path.join("answer-#{id}.yml"))
        rescue StandardError
          nil
        end

        def load_file(filename)
          File.open(filename, 'r') do |file|
            record = YAML.unsafe_load(file.read)
            record.created_at ||= File.ctime(filename)
            record
          end
        end

        def build_record
          Record.new(_id: SecureRandom.uuid)
        end

        def store_record(record)
          filename = path.join("answer-#{record[:_id]}.yml")
          File.open(filename, 'w') do |file|
            file.write YAML.dump(record)
          end
          record.created_at ||= File.ctime(filename)
        end

        def storage
          Dir[path.join("*.yml")]
        end

        def entity(record)
          entity_class.new(**record.to_h).tap(&:enhance_by_dsl)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
quby-5.6.7 lib/quby/answers/repos/disk_repo.rb
quby-5.6.6 lib/quby/answers/repos/disk_repo.rb
quby-5.6.5 lib/quby/answers/repos/disk_repo.rb
quby-5.6.3 lib/quby/answers/repos/disk_repo.rb
quby-5.6.2 lib/quby/answers/repos/disk_repo.rb
quby-5.6.1 lib/quby/answers/repos/disk_repo.rb
quby-5.6.0 lib/quby/answers/repos/disk_repo.rb