Sha256: 5d8205b968c3e6ccd4ed744032185743cff38cc3d999e7b8644de59da3a5908d

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

require 'fileutils'
require 'xing/specdoc/document'
require 'xing/specdoc/winnower'

module Xing
  module SpecDoc
    class DocFamily
      def initialize(name)
        @name = name
        @docs = []
        @index = 1
        @out_stream = $stdout
      end

      attr_reader :name, :docs
      attr_accessor :out_stream

      def add(doc)
        @docs << doc
      end

      def old_doc_glob
        File::join(Xing::SpecDoc.response_target_dir, name) + "*"
      end

      def old_doc_paths
        @old_doc_paths ||= dir_glob(old_doc_glob).find_all do |path|
          re = /#{Regexp.escape(name)}-\d+\.json$/
          path =~ re
        end
      end

      def old_docs
        old_doc_paths.map do |path|
          Document.new(path, File.read(path))
        end
      end

      def record
        ensure_target_dir

        winnower = Winnower.new(docs, old_docs)

        winnower.obsolete_paths.each do |path|
          kill(path)
        end

        winnower.kept_new.each do |doc|
          write(doc)
        end
      end

      def next_output_path
        loop do
          candidate = File::join(Xing::SpecDoc.response_target_dir, "#{name}-#{@index}.json")
          if exist?(candidate)
            @index += 1
          else
            return candidate
          end
        end
      end

      def ensure_target_dir
        FileUtils.mkdir_p(File.dirname(File::join(Xing::SpecDoc.response_target_dir, name)))
      end

      def kill(path)
        @out_stream.puts "Removing outdated JSON example at #{path}"
        FileUtils::rm_f(path)
      end

      def write(doc)
        path = next_output_path
        @out_stream.puts "Writing new JSON example to       #{path}"
        File.write(path, doc.pretty_body)
      end

      def dir_glob(pattern)
        Dir.glob(pattern)
      end

      def exist?(path)
        File.exist?(path)
      end

      def read(path)
        File.read(path)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
xing-backend-specdoc-1.0.0.pre.beta lib/xing/specdoc/doc-family.rb
xing-backend-specdoc-0.0.2 lib/xing/specdoc/doc-family.rb
xing-backend-specdoc-0.0.1 lib/xing/specdoc/doc-family.rb