Skip to content

Instantly share code, notes, and snippets.

@ta
Created October 25, 2025 12:57
Show Gist options
  • Select an option

  • Save ta/99e064feb26fd28eae3ed1b8341bf8e6 to your computer and use it in GitHub Desktop.

Select an option

Save ta/99e064feb26fd28eae3ed1b8341bf8e6 to your computer and use it in GitHub Desktop.
Parse OpenAPI YAML files referencing other files
require "psych"
class OpenAPI < Hash
class << self
def load_yaml_file(file)
self[traverse(parse_yaml_file(file), File.dirname(file))]
end
private
def parse_yaml_file(file)
Psych.load_file(file, aliases: true)
end
def traverse(hsh, dir)
hsh.each do |key, val|
if key == "$ref" # Handle references to external files
file = val.split("#").first
hsh = Dir.chdir(dir) do
traverse(parse_yaml_file(file), File.dirname(file))
end
else
case val
when Hash
hsh[key] = traverse(val, dir)
when Array
val.map! { |x| [Array, Hash].include?(x.class) ? traverse(x, dir) : x }
end
end
end
hsh
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment