How to cache JSON in ruby ​​on rails?

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

  • html template
  • json data
  • javascript to display data in a template (I use PURE )

json data calculated using helper methods (rails and my own) is quite large and often does not change (in the general case, this is the footer, header and some other parts of the page), so it should be cached. What is the right way to do this?

I tried 3 approaches.

and.

 - 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?

AT.

 - 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: the second request is sent to the server ...

WITH.

 - 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 the result of this script to a variable that I can use in javascript that displays data in a template?

B C ( json-), .

? ?

.

+5
1

, . , , , -...

A Rails.

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

...

+17

All Articles