Class: OpenapiRuby::Core::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/openapi_ruby/core/document.rb

Constant Summary collapse

MIN_OPENAPI_VERSION =
"3.1.0"
DEFAULT_OPENAPI_VERSION =
"3.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(info: {}, servers: [], openapi_version: DEFAULT_OPENAPI_VERSION) ⇒ Document

Returns a new instance of Document.



11
12
13
14
15
16
17
18
19
# File 'lib/openapi_ruby/core/document.rb', line 11

def initialize(info: {}, servers: [], openapi_version: DEFAULT_OPENAPI_VERSION)
  validate_version!(openapi_version)
  @data = {
    "openapi" => openapi_version,
    "info" => normalize_info(info),
    "paths" => {}
  }
  @data["servers"] = servers.map { |s| s.transform_keys(&:to_s) } if servers.any?
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



9
10
11
# File 'lib/openapi_ruby/core/document.rb', line 9

def data
  @data
end

Instance Method Details

#add_path(template, path_item) ⇒ Object



21
22
23
24
# File 'lib/openapi_ruby/core/document.rb', line 21

def add_path(template, path_item)
  @data["paths"][template] ||= {}
  @data["paths"][template].merge!(path_item)
end

#set_components(components) ⇒ Object



26
27
28
# File 'lib/openapi_ruby/core/document.rb', line 26

def set_components(components)
  @data["components"] = components if components.any?
end

#set_security(security) ⇒ Object



30
31
32
# File 'lib/openapi_ruby/core/document.rb', line 30

def set_security(security)
  @data["security"] = security if security.any?
end

#set_tags(tags) ⇒ Object



34
35
36
# File 'lib/openapi_ruby/core/document.rb', line 34

def set_tags(tags)
  @data["tags"] = tags if tags.any?
end

#to_hObject



38
39
40
41
42
43
44
45
46
# File 'lib/openapi_ruby/core/document.rb', line 38

def to_h
  result = @data.dup
  result["paths"] = result["paths"].sort.to_h if result["paths"]
  if result["components"]
    result["components"] = result["components"].transform_values { |v| v.sort.to_h }
  end
  result["tags"] = result["tags"].sort_by { |t| t["name"].to_s } if result["tags"]
  result
end

#to_json(*_args) ⇒ Object



48
49
50
# File 'lib/openapi_ruby/core/document.rb', line 48

def to_json(*_args)
  JSON.pretty_generate(@data)
end

#to_yamlObject



52
53
54
55
# File 'lib/openapi_ruby/core/document.rb', line 52

def to_yaml
  require "yaml"
  @data.to_yaml
end

#valid?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/openapi_ruby/core/document.rb', line 57

def valid?
  validate.empty?
end

#validateObject



61
62
63
64
65
66
# File 'lib/openapi_ruby/core/document.rb', line 61

def validate
  schemer = JSONSchemer.openapi(@data)
  schemer.validate.to_a
rescue => e
  [{"error" => e.message}]
end