如果值为 nil,我如何告诉 Rails inmemory cache 不要创建条目?

How do I tell Rails inmemory cache not to create an entry if the value is nil?

我正在使用Rails 5.我想使用Rails内存存储缓存来缓存数据,但是,如果数据的值我不想缓存这样的数据是零。我该怎么做呢?我想我可以扩展 Rails 缓存并编写我自己的方法,所以我找到了下面的代码

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

然而,这似乎不适用于 Raisl 5。当我调用 "fetch_no_nil" 方法时出现以下错误 ...

Please use `normalize_key` which will return a fully resolved key.
 (called from fetch_no_nil at /Users/davea/Documents/workspace/myproject/config/initializers/enhanced_cache.rb:7)
NoMethodError: undefined method `find_cached_entry' for #<ActiveSupport::Cache::MemoryStore:0x007fa6b92ae088>
    from /Users/davea/Documents/workspace/myproject/config/initializers/enhanced_cache.rb:9:in `fetch_no_nil'
    from /Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:116:in `get_cached_content'
    from /Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:73:in `get_url'
    from (irb):1
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/console.rb:65:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/console_helper.rb:9:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

是否有另一种方法可以指示我的 Rails 缓存在值为 nil 时不创建条目?

不要 monkeypatch ActiveSupport::Cache。只需编写一个包装器方法:

def self.cache_unless_nil(key, value)
  Rails.cache.fetch(key) { value } unless value.nil?
end

然后通过调用包装器缓存对象:

cache_unless_nil("foo", "bar")
Rails.cache.fetch("foo")
#=> "bar"
cache_unless_nil("baz", nil)
Rails.cache.fetch("baz")
#=> nil