Sha256: bcbf81a90f3a377f50b9989390217e38515c6f4e5c18384b86bc0bb884f9436b

Contents?: true

Size: 974 Bytes

Versions: 16

Compression:

Stored size: 974 Bytes

Contents

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.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
    unless comment.end_with?("\n")
      comment << "\n"
    end
    "#{comment.gsub(/^/, '# ').gsub(/^# \n/, "#\n")}#{content}"
  end

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

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
rspec-openapi-0.7.2 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.7.1 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.7.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.6.1 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.6.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.5.1 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.5.0 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.8 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.7 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.6 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.5 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.4 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.3 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.2 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.1 lib/rspec/openapi/schema_file.rb
rspec-openapi-0.4.0 lib/rspec/openapi/schema_file.rb