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

时间:2017-04-18 20:47:51

标签: ruby-on-rails caching null ruby-on-rails-5 in-memory

我正在使用Rails 5.我想使用Rails内存存储缓存来缓存数据,但是,如果数据的值为nil,我不想缓存这些数据。我该怎么做呢?我thoguth我coudl扩展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>'

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

1 个答案:

答案 0 :(得分:0)

不要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