Reputation: 7414
I've a .js
file in my public/javascript
folder, I want to include a dynamicaly generated value in this file.
Is it possible to have a .js file dynamicaly generated, something like public/javascript/my_javascript.js.erb
Thanks
Upvotes: 1
Views: 3156
Reputation: 3345
Yea don't do it, you are much better off keeping the code static and using rails to generate data, in say the form of a JSON.
Upvotes: 2
Reputation: 12272
No, not in /public. But you can generate a js file from a standard Rails action, if you like. I wouldn't recommend this, because mixing backend with javascript code is one of the fastest ways to create an unmaintainable and confusing application.
A better solution might be to render a script tag in your layout (above the js includes) to dynamically set a js variable. Then use MY_VAR wherever you need it in the js.
<% javascript_tag do -%>
var MY_VAR = '<%= value_of_my_var || "defaultVal" %>';
<% end -%>
Upvotes: 7
Reputation: 10574
How about a javascript controller as detailed in this railscast:
http://railscasts.com/episodes/88-dynamic-select-menus
Now if you want to only instantiate this dynamic value at runtime then you could cache it or store in an instance variable, depending on where the data's coming from.
You can keep your existing javascript having it by storing the rails variable in a js variable in the dynamic file, as long as page load completed.
Upvotes: 4