Skip to content

Commit

Permalink
Merge pull request #171 from lzap/introduce-cache
Browse files Browse the repository at this point in the history
Introduce cache to speed things up and cleanup method
  • Loading branch information
bastelfreak authored Jul 19, 2021
2 parents 69e7c30 + 4da6b1f commit 763f6bb
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/facterdb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ def self.database
@database ||= "[#{facterdb_fact_files.map { |f| read_json_file(f) }.join(',')}]\n"
end

# @note Call this method at the end of test suite, for example via after(:suite), to reclaim back the memory required to hold json data and filter cache
def self.cleanup
@database = nil
Thread.current[:facterdb_last_filter_seen] = nil
Thread.current[:facterdb_last_facts_seen] = nil
end

# @return [Boolean] - returns true if we should use the default facterdb database, false otherwise
# @note If the user passes anything to the FACTERDB_SKIP_DEFAULTDB environment variable we assume
# they want to skip the default db
Expand Down Expand Up @@ -123,8 +130,16 @@ def self.valid_filters?(filters)

# @return [Array] - array of hashes of facts
# @param filter [Object] - The filter to convert to jgrep string
def self.get_facts(filter=nil)
def self.get_facts(filter=nil, cache=true)
if cache && filter && filter == Thread.current[:facterdb_last_filter_seen]
return Thread.current[:facterdb_last_facts_seen]
end
filter_str = generate_filter_str(filter)
JGrep.jgrep(database, filter_str).map { |hash| Hash[hash.map{ |k, v| [k.to_sym, v] }] }
result = JGrep.jgrep(database, filter_str).map { |hash| Hash[hash.map{ |k, v| [k.to_sym, v] }] }
if cache
Thread.current[:facterdb_last_filter_seen] = filter
Thread.current[:facterdb_last_facts_seen] = result
end
result
end
end

0 comments on commit 763f6bb

Please sign in to comment.