Sha256: 60c9738d41ca741d2edfdbdeb2ab40664f87c6080dc224d8d60d829219c62748

Contents?: true

Size: 1.53 KB

Versions: 7

Compression:

Stored size: 1.53 KB

Contents

module Lurker
  module Json
    class Writter
      class << self
        def write(schema, path)
          new(path).write(schema)
        end
      end

      def initialize(path)
        @path = path
        @dirname = File.dirname(path)
      end

      def write(schema)
        write_to_file(schema)

        extract_references(schema).each do |reference|
          Lurker::Json::Writter.write(reference, reference.original_uri.path)
        end
      end

      private

      # TODO : Separate schema dumping for JSON & YAML files
      def write_to_file(schema)
        FileUtils.mkdir_p(@dirname) unless File.directory?(@dirname)
        File.open(@path, File::WRONLY | File::TRUNC | File::CREAT) do |file|
          file.write(present_by_extension schema)
        end
      end

      def extract_references(schema, memo = [])
        case schema
        when Array
          schema.each { |payload| extract_references(payload, memo) }
        when Hash, Lurker::Json::Schema
          schema.each do |_, payload|
            memo << payload if payload.is_a?(Lurker::Json::Reference)
            extract_references(payload, memo)
          end
        else
          # no-op
        end

        memo
      end

      def present_by_extension(schema)
        case File.extname(@path)
        when '.yml' then schema.to_yaml(reference: :original)
        when '.json' then JSON.pretty_generate(schema.to_hash reference: :original)
        else raise TypeError, "Unknown schema file extension '#{File.extname(@path)}'"
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
lurker-0.6.9 lib/lurker/json/writter.rb
lurker-0.6.8 lib/lurker/json/writter.rb
lurker-0.6.7 lib/lurker/json/writter.rb
lurker-0.6.6 lib/lurker/json/writter.rb
lurker-0.6.5 lib/lurker/json/writter.rb
lurker-0.6.4 lib/lurker/json/writter.rb
lurker-0.6.3 lib/lurker/json/writter.rb