Skip to content

Commit 9142a81

Browse files
committed
Cache file reads
1 parent 1e84c2e commit 9142a81

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

lib/json_matchers/matcher.rb

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,24 @@ def validation_failure_message
1919
errors.first.to_s
2020
end
2121

22+
class << self
23+
attr_writer :document_store
24+
25+
def document_store
26+
@document_store ||= begin
27+
document_store = JsonSchema::DocumentStore.new
28+
29+
Dir.glob("#{JsonMatchers.schema_root}/**/*.json").
30+
map { |path| Pathname.new(path) }.
31+
map { |schema_path| Parser.new(schema_path).parse }.
32+
map { |schema| document_store.add_schema(schema) }.
33+
each { |schema| schema.expand_references!(store: document_store) }
34+
35+
document_store
36+
end
37+
end
38+
end
39+
2240
private
2341

2442
attr_accessor :errors
@@ -29,15 +47,7 @@ def validator
2947
end
3048

3149
def build_and_populate_document_store
32-
document_store = JsonSchema::DocumentStore.new
33-
34-
Dir.glob("#{JsonMatchers.schema_root}/**/*.json").
35-
map { |path| Pathname.new(path) }.
36-
map { |schema_path| Parser.new(schema_path).parse }.
37-
map { |schema| document_store.add_schema(schema) }.
38-
each { |schema| schema.expand_references!(store: document_store) }
39-
40-
document_store
50+
self.class.document_store
4151
end
4252
end
4353
end

spec/json_matchers/match_json_schema_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@
5959
expect(json).to match_json_schema("api/v1/schema")
6060
end
6161

62+
it "does not reload document store" do
63+
create(:schema, :location, name: "api/v1/schema")
64+
65+
json = build(:response, :location)
66+
67+
expect(Dir).to receive(:glob).once.and_call_original
68+
2.times do
69+
expect(json).to match_json_schema("api/v1/schema")
70+
end
71+
end
72+
6273
it "supports invalidating the referenced schema when using local references" do
6374
create(:schema, name: "post", json: {
6475
"$schema": "https://json-schema.org/draft-04/schema#",

0 commit comments

Comments
 (0)