Cache with expiring keys
Asked Answered
C

2

5

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?

Complexion answered 11/8, 2013 at 13:45 Comment(0)
B
10

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
Blinding answered 11/8, 2013 at 14:0 Comment(0)
C
3

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
Commendation answered 11/8, 2013 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.