我如何告诉Rails Inmemory Cache如果值为零,则不要创建条目



我正在使用Rails 5.我想使用Rails In-Memory Store Cache用于缓存数据,但是,如果数据的值为NIL,我不想缓存此类数据。我该怎么做呢?我thoguth我coudl扩展了铁轨缓存并编写自己的方法,所以我找到了以下代码

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

但是,当我调用" fetch_no_nil"方法...

时,这似乎在RAISL5上似乎不起作用。
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>'

是否有另一种方法可以指示我的导轨缓存,如果值不为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

相关内容

  • 没有找到相关文章

最新更新