I am in the process of prototyping a web application using ruby on rails.
I’m a complete newbie to rails, but this question relevant to MVC programming in general.
In the past, when my model held some relevant information that needed to be accessible from my javascript files, I would have some inline javascript in my template and dump it to a global variable thusly:
<script type="text/javascript">
var nodes=<%= @nodes.to_json.html_safe %>;
</script>
However, in production my plan is to use uglifier to compress my javascript files, my guess is that it will not know to rename the nodes variable in my erb files to be in sync with the minified javascript.
(I’m thinking storing it in a named hidden input might get around the minification problem, but feels even hackier…)
So my question is:
Can you suggest any more graceful alternatives to storing page state than dumping json objects in the global namespace?
Preferably in rails, but I’m also interested to see how people solve this problem in other mvc frameworks…
Thanks
Inline JavaScript is awful. That goes double when you’re creating JS values as strings. It creates maintainability problems and should be banished from your bag of tricks forever. JavaScript belongs in external JavaScript files, and those files should be static.
What you want instead is something like:
(view file)
(CSS)
(JavaScript)
This is true regardless of your server-side language.
Bonus Rails-specific tips: use Haml instead of ERb, and Sass instead of CSS. Much nicer.