Reputation: 135
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>
Upvotes: 2
Views: 4036
Reputation: 10154
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
Upvotes: 0
Reputation: 1941
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
Upvotes: 5