如何在rails上的ruby中緩存JSON?

[英]How to cache JSON in ruby on rails?


I am confused about how to use json in my rails (2.3.5) app. These are the elements that I need:

我很困惑如何在我的rails(2.3.5)應用程序中使用json。這些是我需要的元素:

  1. html template
  2. HTML模板
  3. json data
  4. json數據
  5. javascript to render data in the template (I use PURE)
  6. javascript在模板中呈現數據(我使用PURE)

json data, calculated using helper methods (rails and my own ones), is quite big and it doesn't change often (in general it's footer, header and some other parts of the page), so it should be cached. What is the right way to do it?

使用輔助方法(rails和我自己的方法)計算的json數據非常大,並且不會經常更改(通常是頁腳,頁眉和頁面的其他部分),因此應該緩存它。這樣做的正確方法是什么?

I tried 3 approaches.

我嘗試了3種方法。

A.

一個。

 - html template and javascript to render data placed in the view html.erb
 - method to get json data placed in the helper
    <script type="text/javascript">
      var data= <%= helper_method %>;
    </script>

Problem: how to cache json data?

問題:如何緩存json數據?

B.

B.

 - html template and javascript to render data placed in the view html.erb
 - method to get json data is a controller action
     def footer
        expires_in(4.hours)
        render :json => { calculated_data }
     end
 - ajax request in javascript
      $.ajax({
        type: "GET",
        url: "<%=footer_path %>",
        success: function(data){
          render json data in html template
        }
      });

Problem: second request send to the server...

問題:第二個請求發送到服務器...

C.

C。

 - html template and javascript to render data placed in the view html.erb
 - method to get json data is a controller action
     def footer
        expires_in(4.hours)
        render :json => { calculated_data }
     end
 - data in javascript
    <script type="text/javascript" src="<%=footer_path %>">
    </script>

Problems: how can I pass result of that script to a variable which I can use in the javascript that renders data in the template?

問題:如何將該腳本的結果傳遞給我可以在模板中呈現數據的javascript中使用的變量?

In case of B and C there is a need to include helpers in the controller (methods for calculating json data), which is quite ugly solution.

在B和C的情況下,需要在控制器中包括幫助器(計算json數據的方法),這是非常難看的解決方案。

What should be the correct solution for this? Which approach is appropiate for this needs?

對此應該是什么正確的解決方案?哪種方法適合這種需求?

Thanks for all suggestions.

謝謝你的所有建議。

1 个解决方案

#1


19  

No responses, but I found a solution. For those who could have similar problem, maybe it will save time for somebody...

沒有回復,但我找到了解決方案。對於那些可能遇到類似問題的人來說,也許會為某人節省時間......

I used approach A and Rails cache. I have a method in helper

我使用了方法A和Rails緩存。我有一個輔助方法

def footer
  return Rails.cache.fetch('footer', :expires_in => 4.hours){
    caluclate_data_with_other_methods.to_json
  }
end

Just this...

只是這個...


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/05/19/4a18098b4a00aadda65a3cdc80aea3a2.html



 
  © 2014-2022 ITdaan.com 联系我们: