2

I am using Rails 4.2.1 and memcached. I can't seem to cache a hash. How do I cache a hash?

irb(main):039:0* 
irb(main):040:0* Rails.cache.fetch("development_test") do
irb(main):041:1* 'hi'
irb(main):042:1> end
Cache read: development_test
Cache fetch_hit: development_test
=> "hi"
irb(main):043:0> Rails.cache.fetch("development_test")
Cache read: development_test
=> "hi"
irb(main):044:0> Rails.cache.fetch("development_test") do
irb(main):045:1* {'x' => 3}
irb(main):046:1> end
Cache read: development_test
Cache fetch_hit: development_test
=> "hi"
irb(main):047:0> Rails.cache.fetch("development_test")
Cache read: development_test
=> "hi"
irb(main):048:0> 
Adobe
  • 12,967
  • 10
  • 85
  • 126
brojsimpson
  • 135
  • 3
  • 9
  • 2
    You're getting the same value (`"hi"`) back because that's the value you cached. That's the value you'll get back until the cache is invalidated (such is the entire point of a cache). If you want to cache a different value you need to either invalidate the cache or use a different key. – Jordan Running May 20 '16 at 23:00

2 Answers2

5

Check documentation: http://apidock.com/rails/ActiveSupport/Cache/Store/fetch

Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned.

But you can use the option force with true:

Rails.cache.fetch("development_test", force: true) do
  {'x' => 3}
end

for rewrite the cache value

William Wong Garay
  • 1,921
  • 18
  • 14
  • This is not working for me `> Rails.cache.fetch("development_test", force: true) { { x: 3 } } NoMethodError: undefined method `call' for nil:NilClass Did you mean? caller from (irb):24:in ''` – HarlemSquirrel Jun 30 '17 at 18:57
0

I was able to cache hashes as JSONs.

def cached_hash
  JSON.parse(
    Rails.cache.fetch("development_test", expires_in: 1.minute) do
      {'x' => 3}.to_json
    end
  )
end
HarlemSquirrel
  • 8,966
  • 5
  • 34
  • 34