Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

- `OpenapiFirst::FileLoader` will now cache the contents of files that have been loaded. This cache
is keyed on the file's path. If you need to reload your OpenAPI definition for tests or server hot
reloading, you can run `OpenapiFirst::FileLoader.clear_cache!`.
Comment on lines +5 to +7
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this something you'd like documented in the README as well? Until now, FileLoader was an implementation detail.

Maybe this should be OpenapiFirst.clear_cache! or something like that?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the changelog should not mention internal APIs, but just what was behavior was changed / improved. I'll merge this PR and might rephrase this part in the next release (till friday).


## 3.2.1

- Don't raise `UnknownQueryParameterError` if request is ignored in tests. Fixes [#441](https://github.com/ahx/openapi_first/issues/441).
Expand Down
27 changes: 21 additions & 6 deletions lib/openapi_first/file_loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,32 @@
module OpenapiFirst
# @!visibility private
module FileLoader
@cache = {}
@mutex = Mutex.new

module_function

def load(file_path)
raise FileNotFoundError, "File not found #{file_path.inspect}" unless File.exist?(file_path)
@cache[file_path] || @mutex.synchronize do
@cache[file_path] ||= begin
raise FileNotFoundError, "File not found #{file_path.inspect}" unless File.exist?(file_path)

body = File.read(file_path)
extname = File.extname(file_path)

body = File.read(file_path)
extname = File.extname(file_path)
return ::JSON.parse(body) if extname == '.json'
return YAML.unsafe_load(body) if ['.yaml', '.yml'].include?(extname)
if extname == '.json'
::JSON.parse(body)
elsif ['.yaml', '.yml'].include?(extname)
YAML.unsafe_load(body)
else
body
end
end
end
end

body
def clear_cache!
@mutex.synchronize { @cache.clear }
end
end
end
Loading