Class: Cache
- Inherits:
-
Object
- Object
- Cache
- Defined in:
- lib/utils/cache.rb
Instance Attribute Summary collapse
-
#last_fetched ⇒ Object
Returns the value of attribute last_fetched.
-
#size ⇒ Object
Returns the value of attribute size.
Instance Method Summary collapse
- #add_entries_to_file(data:) ⇒ Object
-
#initialize(path:) ⇒ Cache
constructor
A new instance of Cache.
- #read_from_file ⇒ Object
- #remove_entries_from_file(ids:) ⇒ Object
- #write_to_file(data:) ⇒ Object
Constructor Details
#initialize(path:) ⇒ Cache
Returns a new instance of Cache.
5 6 7 8 9 10 11 12 13 |
# File 'lib/utils/cache.rb', line 5 def initialize(path:) @config = { :path => path } @size = File.readable?(@config[:path]) ? JSON.parse(File.read(@config[:path]).to_s)["data"].count : 0 @last_fetched = File.readable?(@config[:path]) ? JSON.parse(File.read(@config[:path]).to_s)["last_fetched"] : nil end |
Instance Attribute Details
#last_fetched ⇒ Object
Returns the value of attribute last_fetched.
3 4 5 |
# File 'lib/utils/cache.rb', line 3 def last_fetched @last_fetched end |
#size ⇒ Object
Returns the value of attribute size.
3 4 5 |
# File 'lib/utils/cache.rb', line 3 def size @size end |
Instance Method Details
#add_entries_to_file(data:) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/utils/cache.rb', line 43 def add_entries_to_file(data:) cache = self.read_from_file new_entries_count = 0 # If an entry doesn't exist in the cache, we add it. data.each do |new_entry| unless cache["data"].find_index { |cache_entry| cache_entry["id"] == new_entry["id"] } cache["data"].push (new_entry.filter { |key| key != "content" }) new_entries_count += 1 end end self.size = cache["data"].count self.last_fetched = Date.today self.write_to_file data: cache puts "#{new_entries_count} new entries were written to cache." end |
#read_from_file ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/utils/cache.rb', line 15 def read_from_file if File.readable? @config[:path] JSON.parse(File.read(@config[:path]).to_s) else return { "size" => 0, "last_fetched" => nil, "data" => Array.new } end end |
#remove_entries_from_file(ids:) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/utils/cache.rb', line 27 def remove_entries_from_file(ids:) cache = self.read_from_file ids.each do |id| # TODO We could implement a search algo like binary search for performance here cache["data"].each do |cached_entry| if cached_entry["id"].to_i == id.to_i cache["data"].delete cached_entry end end end self.size = cache["data"].count self.write_to_file data: cache end |
#write_to_file(data:) ⇒ Object
62 63 64 65 66 |
# File 'lib/utils/cache.rb', line 62 def write_to_file(data:) data["size"] = @size data["last_fetched"] = @last_fetched File.write(@config[:path], data.to_json) end |