Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use CoffeeScript in the views executed on render.js?

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?

like image 821
Geo Avatar asked Jun 03 '11 09:06

Geo


1 Answers

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.

like image 198
Trevor Burnham Avatar answered Sep 17 '22 20:09

Trevor Burnham