What do I need to do so that I can use CoffeeScript in the Rails JS views? For example:
def index
format.js { render :layout => false }
end
What would I need to do in order for Rails to use index.js.coffee
?
Johnny's answer is correct. If you look at the pull request linked to from the CoffeeBeans page, you have dhh saying
Once we have a fast, clean implementation, it's welcome in core. 3.2 is a more likely target, though.
I briefly talked with Sam Stephenson and Josh Peek about this at Railsconf, since this was a missing feature people had asked me about after my CoffeeScript talk. After all, Rails 3.1 is pushing CoffeeScript as a default pretty hard; it seems odd that there are places where pure JS has to be used. Sam's reaction was that this wouldn't be efficient, because you'd have to fire up the CoffeeScript compiler on every page request, even in production. That's because code like
<%= coffee_script_tag do %>
alert "coffee script is #{verb}!"
<% end %>
creates an ERB interpolation (not a CoffeeScript interpolation—unfortunate that both use the same syntax), potentially yielding a different string of CoffeeScript code on every request. And there's no way to tell, from the coffee_script_tag
implementation, whether the given code is going to be the same every time (i.e. whether there's an ERB interpolation or not).
Now, the CoffeeScript compiler is very fast, but compiling to JavaScript is still going to add a little extra time to each request. So the Rails team is hesitant to encourage the practice.
For the sake of efficiency, and to avoid the ambiguity between ERB interpolations and CoffeeScript interpolations, you should probably keep your CoffeeScript somewhere (perhaps as a .coffee
file in the same directory as your view) and compile it to JavaScript by hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With