Skip to content

Commit 222cbfa

Browse files
author
Tessa Bradbury
authored
Cache VRT::Map objects (#18)
1 parent f542770 commit 222cbfa

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

lib/vrt.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ module VRT
2121

2222
@version_json = {}
2323
@last_update = {}
24+
@maps = {}
2425

2526
module_function
2627

@@ -52,7 +53,7 @@ def last_updated(version = nil)
5253
end
5354

5455
def current_categories
55-
Map.new(current_version).categories
56+
get_map.categories
5657
end
5758

5859
# Get all deprecated ids that would match in the given categories from the current version
@@ -76,8 +77,8 @@ def all_matching_categories(categories)
7677
# @return [VRT::Node|Nil] A valid VRT::Node object or nil if no best match could be found
7778
def find_node(vrt_id:, preferred_version: nil, max_depth: 'variant', version: nil) # rubocop:disable Lint/UnusedMethodArgument
7879
new_version = preferred_version || current_version
79-
if Map.new(new_version).valid?(vrt_id)
80-
Map.new(new_version).find_node(vrt_id, max_depth: max_depth)
80+
if get_map(version: new_version).valid?(vrt_id)
81+
get_map(version: new_version).find_node(vrt_id, max_depth: max_depth)
8182
elsif deprecated_node?(vrt_id)
8283
find_deprecated_node(vrt_id, preferred_version, max_depth)
8384
else
@@ -93,6 +94,11 @@ def get_json(version: nil, other: true)
9394
other ? @version_json[version] + [OTHER_OPTION] : @version_json[version]
9495
end
9596

97+
def get_map(version: nil)
98+
version ||= current_version
99+
@maps[version] ||= Map.new(version)
100+
end
101+
96102
# Get names of directories matching lib/data/<major>-<minor>/
97103
def json_dir_names
98104
DIR.entries
@@ -121,6 +127,7 @@ def reload!
121127
unload!
122128
versions
123129
get_json
130+
get_map
124131
last_updated
125132
mappings
126133
end
@@ -130,6 +137,7 @@ def unload!
130137
@versions = nil
131138
@version_json = {}
132139
@last_update = {}
140+
@maps = {}
133141
@mappings = nil
134142
end
135143
end

spec/vrt_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@
3232
end
3333
end
3434

35+
describe '#get_map' do
36+
it 'takes a vrt version number and returns a VRT::Map' do
37+
expect(described_class.get_map(version: '1.0')).to be_a(VRT::Map)
38+
end
39+
40+
it 'only creates the map once' do
41+
expect(VRT::Map).to receive(:new).once.and_return('dummy map')
42+
expect(described_class.get_map(version: '1.0')).to eq('dummy map')
43+
expect(described_class.get_map(version: '1.0')).to eq('dummy map')
44+
end
45+
end
46+
3547
describe '#last_update' do
3648
it 'shows the last updated time from version metadata' do
3749
expect(described_class.last_updated).to eq Date.parse('Tue, 17 Feb 3001')

0 commit comments

Comments
 (0)