Skip to content

Commit

Permalink
Add the rails low level caching post
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammad AbuShady committed Apr 2, 2015
1 parent 4786075 commit 1182475
Showing 1 changed file with 17 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
title: Using rails low level caching
layout: post
ident: using-rails-low-level-caching
published: true
---
Some times we find our selves having a time expensive method or in some cases
using an API that costs money per request, or a slow one, I had that issue once
Expand All @@ -20,31 +21,36 @@ with `write`
`write` takes two arguments, a cache key ( the key we're going to use to
retrieve the data ) and a cache value ( the data that's going to be stored ),
here's a simple example

Rails.cache.write 'my_caching_key', some_data
{% gist e382b9d3fdda2e90c5ab basic_write.rb %}
Now this data is cached and can be retrieved when needed, there's also extra
options that can be passed such as expiry period

Rails.cache.write 'my_caching_key', some_data, expires_in: 1.hour
{% gist e382b9d3fdda2e90c5ab write_with_expire.rb %}
When the cache expires it will return nil when accessed.

The caching key could also be an object, not necessarily a string, for example
the key could be an object, or an array, or a hash, for example

Rails.cache.write(['some_data', @user], some_data)
Rails.cache.write({key: 'important_data', owner: @user}, some_data)
{% gist e382b9d3fdda2e90c5ab write_with_compund_key.rb %}
You get the idea.

##Read
`read` only takes the cache key to retrieve the data, if the data doesn't exist,
`nil` will be returned instead

Rails.cache.read 'my_caching_key'
{% gist e382b9d3fdda2e90c5ab basic_read.rb %}
Also like `write`, you can use the non scalar key type to retrieve the data you
saved in the same way

Rails.cache.read({key: 'important_data', owner: @user})
{% gist e382b9d3fdda2e90c5ab read_with_compund_key.rb %}

##Fetch
`fetch` is a little special, because it does both `read` and `write`, when the
cache exists it returns it, but if it isn't it evaluates the block it's given
then writes the result to the cache and returns the value at the same time, if
the block isn't expensive ( in terms of time ) you could do with only fetch.
{% gist e382b9d3fdda2e90c5ab fetch_with_block.rb %}
If `some_key` is present and not stale, it's returned instantly from the cache,
if it is, the block is evaluated ( `some_calculations` ) and the return value
from the block is saved in the `some_key`

Of course as you can see all options mentioned before are also applicable on the
`fetch` method

[rails-low-level-caching-url]: http://guides.rubyonrails.org/caching_with_rails.html#low-level-caching

0 comments on commit 1182475

Please sign in to comment.