pchu
pchu

Reputation: 181

Rails continues to cache when the value is nil

Rails 3.2.13 cache key for when the value is nil. Have been looking at docs to find if there are any options to set to stop this behavior, but couldn't find any.

Is there anyway to stop Rails from caching a key when the value is nil?

1.8 :001 > value = nil
 => nil 
1.8 :002 > Rails.cache.fetch('foo'){value}
 => nil 
1.8 :003 > value = true
 => true 
1.8 :004 > Rails.cache.fetch('foo'){value}
 => nil

Upvotes: 2

Views: 2286

Answers (3)

jBilbo
jBilbo

Reputation: 1703

Updated answer: cache_nils option is what you're looking for. Check the cache store you're using in case it doesn't support it, but for dalli_store works:

1.8 :001 > value = nil
 => nil 
1.8 :002 > Rails.cache.fetch('foo'){ value }
 => nil 
1.8 :003 > value = true
 => true 
1.8 :004 > Rails.cache.fetch('foo', cache_nils: false){ value }
 => true

Upvotes: 0

Rafa Paez
Rafa Paez

Reputation: 4870

There is not in-build option in Rails cache to do that, so I would use a custom method to accomplish what you want, like the following:

def fetch(key, value)
  if Rails.cache.exist?(key)
    Rails.cache.read(key)
  else 
    Rails.cache.write(key, value) unless value.nil?
  end
end

fetch('foo', nil)
# => nil
fetch('foo', true)
# => true

Upvotes: 3

vdaubry
vdaubry

Reputation: 11439

Not sure to understand what's the problem, nil values will be ignored :

Rails.cache.fetch('foo') { nil }
Cache read: foo
Cache generate: foo
Cache write: foo
 => nil 

Rails.cache.fetch('foo'){ "bar" }
Cache read: foo
Cache generate: foo
Cache write: foo
 => "bar" 

Rails.cache.fetch('foo'){ nil }
Cache read: foo
Cache fetch_hit: foo
 => "bar" 

Upvotes: 0

Related Questions