Rails asset pipeline: How to prevent caching of a specific asset

别说谁变了你拦得住时间么 提交于 2019-12-10 19:18:18

问题


As stated in the title I want to prevent caching of a specific asset, namely a javascript file something.js.erb. The situation is like as follows:

Content of something.js.erb:

...
var something = <%= SomethingHelper.get_something.to_json %>;
...

It binds the value from SomethingHelper successfully but only once and unless the javascript file is edited by hand the value of var something is never assigned again.

This might be somehow expected but clearly doesn't meet my needs. Output of SomethingHelper.get_something changes according to call time. So I need to see up-to-date data in my compiled something.js file.

My exact need:

  • I don't want to disable asset pipeline caching as a whole
  • I only want something.js.erb to be rendered every time it is requested.

is this even possible?

Environment info:

  • Rails 4
  • Development mode
  • Rails' own server but will be on nginx on prod

Thanks


回答1:


I can suggest 2 options:

1)Use inline js to set variable:

<%= javascript_tag do %>
  window.something = '<%= j SomethingHelper.get_something.to_json %>';
<% end %>

2)Store the variable in your html and call it from your js:

#html

<body data-something="<%= j SomethingHelper.get_something.to_json %>">
</body>

#js

$("body").data("something");



回答2:


You're marrying front-end business logic with data. This is inadvisable, and one of the reasons I don't use or recommend using ERB + JS for most scenarios (especially triggering behavior on response like Rails tutorials and guides are keen on doing). You are better off either…

  1. Firing a request off to fetch the data from your JavaScript.
  2. Provided the variable is going to be used on every page (or close to it) and is relatively brief, non-binary data, you can embed a meta tag in your layout with the relevant information.

For example:

# /app/views/layouts/application.html.erb
<%= tag :meta, name: 'something', content: @something %>

# /app/assets/javascripts/application.js
$('meta[name="something"]').attr('content');


来源:https://stackoverflow.com/questions/16731329/rails-asset-pipeline-how-to-prevent-caching-of-a-specific-asset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!