Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top