Achaius
Achaius

Reputation: 6124

How to prevent storing nil value in rails cache?

I am using redis-store for caching in my application,I don't want to fetch the key and value if the value returns nil.

Rails.cache.fetch{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end

if it return the nil for the key "user_by_comment_id:#{params['comment_id']}",I don't want to store the key in my cache.Help me to solve this.

Upvotes: 11

Views: 3869

Answers (2)

Van_Paitin
Van_Paitin

Reputation: 4248

Update:

From rails 6.0.0, you can supply the skip_nil: true option while calling Rails.cache.fetch

Here

Thanks Rick Suggs for pointing this out.

Upvotes: 18

Sucrenoir
Sucrenoir

Reputation: 3034

You can add methods in the Rails.cache class to handle your case (put that code in initializer somewhere):

   module ActiveSupport
   module Cache
    class Store
      def fetch_no_nil(name, options = nil)
        if block_given?
          options = merged_options(options)
          key = namespaced_key(name, options)

          cached_entry = find_cached_entry(key, name, options) unless options[:force]
          entry = handle_expired_entry(cached_entry, key, options)

          if entry
            get_entry_value(entry, name, options)
          else
            save_block_result_to_cache_if_not_nil(name, options) { |_name| yield _name }
          end
        else
          read(name, options)
        end
      end
      private
      def save_block_result_to_cache_if_not_nil(name, options)
        result = instrument(:generate, name, options) do |payload|
          yield(name)
        end
        write(name, result, options) unless result.nil?
        result
      end
    end
  end
  end

And then use :

Rails.cache.fetch_no_nil{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end

Upvotes: 5

Related Questions