Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache with expiring keys

I'm working on a mashup site and would like to limit the number of fetches to scrape the source sites. There is essentially one bit of data I need, an integer, and would like to cache it with a defined expiration period.

To clarify, I only want to cache the integer, not the entire page source.

Is there a ruby or rails feature or gem that already accomplishes this for me?

like image 394
Jeff Axelrod Avatar asked Dec 20 '22 01:12

Jeff Axelrod


2 Answers

Yes, there is ActiveSupport::Cache::Store

An abstract cache store class. There are multiple cache store implementations, each having its own additional features. See the classes under the ActiveSupport::Cache module, e.g. ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most popular cache store for large production websites.

Some implementations may not support all methods beyond the basic cache methods of fetch, write, read, exist?, and delete.

ActiveSupport::Cache::Store can store any serializable Ruby object.

http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

cache = ActiveSupport::Cache::MemoryStore.new
cache.read('Chicago')   # => nil 
cache.write('Chicago', 2707000)
cache.read('Chicago')   # => 2707000

Regarding the expiration time, this can be done by passing the time as a initialization parameter

cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)

If you want to cache a value with a different expiration time, you can also set this when writing a value to the cache

cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
like image 65
Konrad Reiche Avatar answered Jan 09 '23 14:01

Konrad Reiche


See Caching with Rails, particularly the :expires_in option to ActiveSupport::Cache::Store.

For example, you might go:

value = Rails.cache.fetch('key', expires_in: 1.hour) do
    expensive_operation_to_compute_value()
end
like image 25
Alistair A. Israel Avatar answered Jan 09 '23 13:01

Alistair A. Israel