Created
October 25, 2025 12:57
-
-
Save ta/99e064feb26fd28eae3ed1b8341bf8e6 to your computer and use it in GitHub Desktop.
Parse OpenAPI YAML files referencing other files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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