Sha256: 6523ec5f3203afcf82e781bd15f9a0bab321e69dba3de312b11aa01e6e87bd27

Contents?: true

Size: 997 Bytes

Versions: 9

Compression:

Stored size: 997 Bytes

Contents

# frozen_string_literal: true

require 'fileutils'
require 'yaml'
require 'json'

# TODO: Support JSON
class RSpec::OpenAPI::SchemaFile
  # @param [String] path
  def initialize(path)
    @path = path
  end

  def edit(&block)
    spec = read
    block.call(spec)
  ensure
    write(spec)
  end

  private

  # @return [Hash]
  def read
    return {} unless File.exist?(@path)

    YAML.safe_load(File.read(@path)) # this can also parse JSON
  end

  # @param [Hash] spec
  def write(spec)
    FileUtils.mkdir_p(File.dirname(@path))
    output =
      if json?
        JSON.pretty_generate(spec)
      else
        prepend_comment(YAML.dump(spec))
      end
    File.write(@path, output)
  end

  def prepend_comment(content)
    return content if RSpec::OpenAPI.comment.nil?

    comment = RSpec::OpenAPI.comment.dup
    comment << "\n" unless comment.end_with?("\n")
    "#{comment.gsub(/^/, '# ').gsub(/^# \n/, "#\n")}#{content}"
  end

  def json?
    File.extname(@path) == '.json'
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rspec-openapi-0.15.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.14.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.13.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.12.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.11.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.10.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.9.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.8.1 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.8.0 lib/rspec/openapi/schema_file.rb