Rails 3.1 — Using ERB/HAML/etc within a Coffeescript JS file
Stamped: 28 May 2011 | Show comments
Need to use some information from your application in your new Coffeescript file? All you have to do is rename it with .erb.coffee or .
$ ->
$('#currency_select').change ->
window.location = window.location.pathname.replace(/^\/(<%=Country.currencies.keys.join '|'%>)|(?!(<%=Country.currencies.keys.join '|'%>))\//i, '/'+$(this + "option:selected").text())
The best part about it is that Rails still knows when to generate the file, it doesn't do it each time! The only thing you can't directly access are the routes (e.g. root_path(), etc), but a gem called js:routes can take care of that for you.