views:

57

answers:

3

Hello,

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

+3  A: 

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.

mark
ryanb's solution is perfect for me, thanks
denisjacquemin
+6  A: 

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 -%>
Jonathan Julian
Good solution thanks, for me the ryanb' solution is better for my needs
denisjacquemin
Yes: this is the right way to go.
Yar
+1  A: 

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.

Zachary K