代码之家  ›  专栏  ›  技术社区  ›  frankodwyer

如何将缓存操作配置为适用于多种格式?

  •  3
  • frankodwyer  · 技术社区  · 15 年前

    我有一个rails操作,它以各种格式响应请求,包括AJAX请求,例如:

       def index
        # do stuff
        respond_to do |format|
          format.html do
            # index.html.erb
          end
          format.js do
            render :update do |page|
              page.replace_html 'userlist', :partial => "userlist", :object=>@users
              page.hide('spinner')
              page.show('pageresults')
            end
          end
        end
       end
    

    我已将此操作设置为使用memcached进行缓存,使用:

     caches_action :index, :expires_in=>1.hour, :cache_path => Proc.new { |c| "index/#{c.params[:page]}/#{c.request.format}" }
    

    这个模式似乎可以很好地缓存HTML结果,但不能缓存JS结果。当JS部分不是来自缓存时,它总是可以正常工作。但是,当缓存命中时,页面不会更新。

    什么可能导致这种情况?解决方法是什么?

    更新:再深入研究一下,它看起来像是从缓存获取mime类型“text/html”而不是“text/javascript”的请求。但是我不知道该如何解决这个问题-这是memcached的一个怪癖吗?(轨道2.3.2)

    3 回复  |  直到 15 年前
        1
  •  2
  •   Philip Cunninghm    12 年前

    类似于voldy的回答,但使用了非弃用的方法。

    caches_action :show,
                  :cache_path => :post_cache_path.to_proc,
                  :expires_in => 1.hour
    
    protected
    
    def post_cache_path
      if request.xhr?
        "#{request.url}.js"
      else
        "#{request.url}.html"
      end
    end
    
        2
  •  0
  •   dombesz    15 年前

    我想我也遇到过类似的问题,如果我将render:update块移到一个rjs文件中,请求会快得多。如果我做这样的渲染,响应时间大约是8秒,在移到rjs模板后是80毫秒。我不太了解memcached,但对我来说,他似乎只能缓存视图,如果你对缓存控制器有任何想法,请与我分享。

        3
  •  0
  •   Voldy    14 年前

    有一个 issue 在rails中,甚至在edge(3.0.1)版本中。

    我可以用这个来解决:

      caches_action :show, :cache_path => :show_cache_path.to_proc
    
      private
    
      def show_cache_path
        if request.accepts[0].to_sym == :html
          "#{request.host_with_port + request.request_uri}.html"
        else
          "#{request.host_with_port + request.request_uri}.js"
        end
      end