I am confused about how to use json in my rails (2.3.5) app. These are the elements that I need:
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?
I tried 3 approaches.
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?
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.
- 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?
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.
What should be the correct solution for this? Which approach is appropiate for this needs?
Thanks for all suggestions.
In order to add data in cache as JSON, the objects need to be created according to the JSON standards provided by NCache. JsonObject is added in the cache against a unique key. This key will be used to perform further operations on the cache.
Rails 5.2 introduced built-in Redis cache store, which allows you to store cache entries in Redis.
Caching means to store content generated during the request-response cycle and to reuse it when responding to similar requests. Caching is often the most effective way to boost an application's performance.
Request Headers 2nd request: Thx for response. Yes you can cache JSON responses.
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
def footer
return Rails.cache.fetch('footer', :expires_in => 4.hours){
caluclate_data_with_other_methods.to_json
}
end
Just this...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With