Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is rails using the .js.coffee extension for coffeescript files when they cannot contain javascript code anyway?

I found that to be rather misleading as I thought it suggest that such files could include a mixture of both javascript and coffeescript code. Is there something very fundamental that I am missing?

like image 386
prusswan Avatar asked Jan 25 '12 10:01

prusswan


People also ask

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

What is .coffee File?

JavaScript file written in CoffeeScript, a programming language that compiles and transcompiles to JavaScript; saved in a text format and contains code that is similar to JavaScript, but modified to be more readable. CoffeeScript's aim is to enhance JavaScript's brevity and readability.

What is Rails CoffeeScript?

CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. The golden rule of CoffeeScript is: “It's just JavaScript.” The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.


2 Answers

It's a common practice in Rails for templates to have extensions like .js.coffee, .html.erb, .html.haml, etc.

If I remember correctly Rails interprets these extensions as .[format].[builder] and uses that knowledge to do two things:

  1. find proper template by [format] value comparing it with acceptable formats listed in the request's Accept header;
  2. find appropriate template processor by [builder] value to parse your template.
like image 102
KL-7 Avatar answered Nov 15 '22 03:11

KL-7


And you can include plain javascript if you use backticks.

Something like `function(){ do something };` would work.

like image 23
rapcal Avatar answered Nov 15 '22 05:11

rapcal