Rails asset pipeline: How to prevent caching of a

2019-07-07 07:43发布

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

2条回答
该账号已被封号
2楼-- · 2019-07-07 08:15

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');
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-07 08:25

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");
查看更多
登录 后发表回答