#267 CoffeeScript Basics
CoffeeScript allows you to write JavaScript in a concise, elegant fashion. Here I convert JavaScript code to CoffeeScript in a Rails 3.1 app.
- Download:
- source codeProject Files in Zip (84 KB)
- mp4Full Size H.264 Video (21 MB)
- m4vSmaller H.264 Video (12.2 MB)
- webmFull Size VP8 Video (14.2 MB)
- ogvFull Size Theora Video (33.9 MB)
no coffee color syntaxing yet in show notes :)
Yeah, too bad CodeRay doesn't include a scanner for it. Ping me on Twitter if anyone is interested in making one.
BTW, I just created the CoffeeScript syntax highliter for highlight.js https://github.com/dnagir/highlightjs-coffeescript
A bit different tool, but might help others I guess.
Ryan, thank you for this awaited episode. I would like to use CoffeeScript in Rails 3.0.7 app. Can anybody suggest how to integrate it?
Barista
hi Vladimir.
In a very fast way you can use guard.
Then your coffeescript compiled in javascript every time you save a .coffee
I m not sure this is the perfect way but it's work and it's easy to implement in rails 3.0.x
I still do not understand why I should learn 3rd and 4th level languages? Why common JavaScript is bad now?
You should not. You just have the option if it seems worthwhile to you.
Same arguments apply to moving to any higher level language.
@Dmitri: JS is not bad at all, no, Coffe Script just makes it easier to write js code. I like it. Same goes for me with html and haml. I stopped using html in favour of haml, as its just cleaner and easier to write.
Ryan, it says 3 Comments, but there are 4 already...
I like sass and scss, but my eyes got pain of haml and coffee. I prefer old good JS and HTML/Erb.
Well, yeah, peoples opinions vary about haml. In the beginning i needed to get used to it too, but now it so much easier code views than it is with html + erb. By far the biggest benefits to me are not having to close tags, and not having to use the messy <%= %>.
"<%= %>" oh my god. my fingers scream every time i hit this key combination (on mac keyboards) ;)
Dmitri: I can't understand either even after a look to this screencast. It just shows you can strip off "function" and things like that but do we need that ?
Who says you need to use Jquery? or Coffeescript? or Haml? or Sass? or Git? or Activerecord? Or ...?
Rails is modular, in fact, I think it is one of the most modular frameworks out there.
Yes, rails comes "packaged" (as in, it has a few extra lines in the Gemfile) with some defaults, it's an opinionated framework, and that's one of the reasons why it's gotten so big so fast, but all that does is make it easier for beginners to jump in and start coding.
Is it really that hard for you to type a few extra characters when you create a new app?
Rails new myapp = Jquery, Cofeescript, Sass, Erb, Activerecord, Test Unit, Git
Rails new myapp -OGJT = ... none of the above, go figure!
It's funny, this is the number one argument for justifying the change. However, if you are a working developer and work on different projects, chances are you will HAVE to learn it if the majority of apps use it.
If you look at most rails apps <= 2.3.x that are currently in production, they most certainly use rails standards of the time. e.g. rails 2.3.x apps use prototype. So, I would say just learn it. You may find you like it...
If you dont want a framework and community with a gold standard you are free to go back to Java or PHP. Like it or not, Rails came up HUGE (and drug Ruby along with it) because DHH, and later the core teams decided on opinionated software. The Golden Path is what separates good rails code from bad more times then not.
For instance, you can jump around just about any auth plugin or roll your own. But if you dont include common idioms for rails authentication it will be unusable by most coders or gems. Do I think current_user is the best helper method name for this? Maybe, maybe not. But I am not going to start rolling my auth modules with anything else. Thank god for Golden Paths.
Oh, and if you are still writing pure javascript I have high doubts that you are very efficient.
This screencast mostly shows how to transition from JavaScript to CoffeeScript. However, CoffeeScript adds a ton of really helpful constructs beyond that which JS provides, cleanly and easily.
The thing I've found best about it is that it brings language features that I use all the time in Ruby (like
unless
, string interpolation using#{}
, improved looping, etc.) ...Mix that all in with the fact that it's more readable and uses fewer characters, well, you have a giant win.We live in a world where web development requires some fluency in multiple languages: HTML, CSS, JavaScript, Ruby, YAML. Providing ways to simplify (SCSS being identical to CSS, but adding new abilities that are easy to pick up and understand, for example) is key to speeding up development. CoffeeScript takes some getting used to, sure, but in the longer term it'll make more readable, easier to maintain and more enjoyable to write code.
@Nicolas: Well, its pretty simple, its nicer and cleaner to use... And you really don't have to use it if you don't want to. Well, and yes, there are choices made by the core rails developers... But Rails is an open project afaik, so you can contribute to those choices if you want. And if you don, fine, but then you might need to find some other tools to use if Rails doesn't suit you...
totally agree with @nico (Ritsche).
i have no idea why everybody is crying because of coffeescript.
thats 1 !!! line you have to comment out when starting a project in rails 3.1 if you don't want to use it.
@Nicolas: You don't have to use any of this stuff. You still can use plain JS. You don't have to use git and you still can use Prototype+Scriptaculous. You are not walled in, just because the defaults are different.
I only said it WILL
@Dmitri @Nicolas: Firstly, I find that learning a new syntax happens with very little effort. For CS, I read a few blog posts upon encountering it and this took perhaps an hour. Then I learn the syntax as I use it and this means I might occasionally have to look up the reference when I get a compile error and can't work out what I have done wrong. Initially this does add some time to development but only a very minimal 5 minutes here and there. Consequently, I don't buy the argument that the difficulty in learning CS is so great, it overwhelms any benefits.
Secondly, I see no reason to treat myself as a human compiler. If I am repeating the same stuff again and again, it is a sign that something could be done programmatically. Unfortunately, this is not always viable in an interpreted language where speed is such an important factor. Additionally, it is difficult to update a language on the client side so where clear improvements are identified, they remain unusable to the developer. CS solves both of these problems. For example, see destructured assignment.
Thirdly, I don't like CS just because it is "prettier". I can take or leave the new function syntax for example. What I do like are the abstractions that clearly make sense and are more readable than the JS alternative. Default arguments, variable safety, splats and comprehensions are enough reason for me to use CS. However, I do like all of the more sugary stuff as well.
Peepcode also has a screencast on Coffeescript for those wishing to see more in-depth examples of Coffeescript usage.
Thanks Ryan for another great screencast. I've already cleaned up a bunch of my javascript and my JS files just feel so much more manageable and readable now.
Ryan, you were at my talk at RailsConf, right? Thanks for finally giving the overview everyone wanted me to provide. :)
As to the discussion of whether learning/using CoffeeScript is worth it: Check out some of the blurbs on my CoffeeScript book, including one from Brendan Eich, the creator of JavaScript (who was kind enough to review a draft and even offered a few corrections).
Yes, there are downsides to using CoffeeScript rather than JavaScript, but the benefits
what exactly are the downsides? thanks for a example ;)
Well, having to go through a compile step is obviously a downside, though Rails makes this very transparent. (And in my experience, many of the things that you get as compile-time errors in CoffeeScript would have been run-time errors in JavaScript, where your typo would have gone unnoticed until you click a particular button... as I say in my book, "The compiler's here to help.")
Perhaps the biggest downside is that your code will become obsolete as new CoffeeScript versions are released. This is, of course, true of almost any language (see: Ruby), but if you're writing pure JavaScript, you can be sure that browsers will continue to run it for as long as the web as we know it exists. CoffeeScript has seen few changes since 1.0 came out in December (1.1.0/1.1.1 mostly just fixed bugs and improved the REPL), but it'll continue to evolve in the future, and that evolution will inevitably break backward compatibility.
Still, being able to write code more quickly and read it more easily is such a huge win that I wouldn't hesitate to use it on almost any project.
Great intro!
BTW I think we should start calling '->' 'dash rockets' as also done in PeepCode's CoffeeScript video: http://peepcode.com/products/coffeescript
i agree!! i loved that screencast, only i use Guard-coffeescript for compiling, seems more straight forward to me.
If anyone really wants to get hit in the head with why CS is now the default, check out DHH's talk at RailsConf, http://www.youtube.com/watch?v=cGdCI2HhfAU
Is there an automated way to convert from javascript to coffeescript??
Ryan, thanks for the intro to CF. I can see that this should lead to code that is quicker to write, and more easy to maintain than pure JS.
Watching how you converted your JS to CS just makes sense. Before I was thinking I could not be bothered but now I think I maybe become a convert.
Thanks Ryan great cast.
Hello guys,
I'm new in RoR and these screencasts are very very nice, thx at Ryan!!!
I saw a screencast about Jasmine and i want to use it. It's a cool GEM to test the JavaScript, but can i use CoffeeScript?
Yes. The PeepCode screencast about CoffeeScript shows how to use it with Jasmine.
Thx!
Thanks Ryan for a great intro to CoffeeScript - I've been eagerly anticipating an episode on this this.
And thank you to Trevor Burnham for your comments. I can see now why I should learn CoffeeScript. It didn't quite click that I'd be moving any syntax errors into compile time until I read your comment. That's a big plus in my opinion. I look forward to buying and reading your book.
As a side note, I've just taken a fresh look at HAML because I started playing around with ActiveAdmin. I must say I really must have been in a bad mood the last time I looked at it because now it really does seem appealing. I will have to play with it a little more too I think (even though it's not a default in the Rails stack)!
If nothing else Rails is teaching me to be more open-minded.
As a side note Ryan, I've noticed our avatars are being cached here at Railscasts. I updated my account at Github months ago and I'm seeing old info here, is there a way we can force a refresh on our profile here at Railscasts?
I know I can edit my profile, but I can't change my Github account.
Great railscast as usual.
Coffeescript looks great! One thing I don't understand: - it appears they were modeling it after ruby. So I wonder why they didn't go all the way, and use def/end, class definitions, same ternary operators etc.
Seems like this would have been a big win - write your entire web app in one language!
Well you could always use Node.js ;)
Touche :)
Great railscast as usual! Thanks Ryan!!!
Does anyone know if writing the view using haml and scss/sass is cross-browser compatible. do I still need to use hacks and tricks to make the view look the same in all browsers?
I know this is a stupid question cause it would tooooo beautiful if it was true ;-)
'dash rockets' RoCK!
You should try using compass for sass. It really made my life easier in terms of x-browser compatibility.
I would also recommend using slim instead of haml. It's just so much pleasure when you save this couple of clicks - and apparently it is faster than haml to compile
Thanks Bart for your post. I've googled on my own also and I came up with couple of tools / frameworks that can help in x-browser compatibility:
1. PIE http://css3pie.com/about/
2. 960 and Adapt.js http://adapt.960.gs/
and of course Compass
Does anyone have any other tools helpful in x-browser compatibility?
Thank you, Ryan! It's great episode!
The only thing about CoffeeScript that I am wary of is that the code you write is not the code that will appear in firebug when you have to debug a problem.
I am not a JS developer (Thank deity for jquery) but I did have to write 300 lines of JQuery/DOM JS recently for a horrendously complicated set of form manipulation functions.
It had 24 test scenarios (Thank deity for Cucumber & Akephalos ) and whenever a problem arose debugging it was a total total pain in the arse.
I honestly doubt I would have been able to debug it if I had to look through compiled JS.
I have the same concern. I really prefer the CoffeeScript syntax to Javascript but it seems I won't be able to escape Javascript entirely when it comes time to debug. What are people using for this? Is there any way to see CoffeeScript in firebug?
The only thing about CoffeeScript that I am wary of is that the code you write is not the code that will appear in firebug when you have to debug a problem.
I am not a JS developer (Thank deity for jquery) but I did have to write 300 lines of JQuery/DOM JS recently for a horrendously complicated set of form manipulation functions.
It had 24 test scenarios (Thank deity for Cucumber & Akephalos ) and whenever a problem arose debugging it was a total total pain in the arse.
I honestly doubt I would have been able to debug it if I had to look through compiled JS.
Hi. How can I access variables in controller from .coffee file?
url: "#{sort_admin_product_images_path(@product}"
In my opinion there is one huge advantage to Coffeescript that hasn't been discussed at all in the comments, and that is that Coffeescript introduces OOP to Javascript.
O.k. Yes, you can do the exact same things you do in Coffeescript just natively in Javascript, but unlike some of Coffeescript's other 'improvements' that just remove a few brackets or parenthesis here and there, Coffeescript's OOP model turns what would otherwise be incomprehensible and arcane code into beautiful, readable, understandable code.
http://jashkenas.github.com/coffee-script/#classes
Once I started taking advantage of Coffeescript classes, I found myself writing Javascript in a totally new innovative way that I had never done before. It isn't just about what can or cannot be done with or without Coffeescript, but more about what Coffeescript inspires you to do through its easy classes and extension framework. You start thinking differently.
I totally agree with you.
I think there should be another railscast to emphasize the real advantages of coffeescript :-)
IMHO a lot of the code that is written in the server side could have been written in the client side, but js can get so ugly and disorganized, that developers (my self included) prefer to write the logic in the server side.
with coffeescript - I believe things can and will be different.
not saying that business logic should be on the client side, but moving more code and calculations to the client side can make your application much more responsive and scalable.
I agree as well, though I'm new with it, I see the potential
The original JS in this example seems to be more readable to me.
Thanks Ryan, very easy to understand. Do you plan on making an episode on Backbone.js soon?
Out of curiosity, how are you compiling your coffeescript from text mate? The rails gem doesn't include a coffee command line utility as far asI can tell, so I get an error when trying to run the coffee command from TM (not a path issue, as "which coffee" results in a blank). Did you install this separately? Any conflicts?
I wonder which color scheme do you use in this video ? I really liked it, it reminds me of coffee with all those shades of brown :)
Ryan, thank you for this episode. I would like to use CoffeeScript in Rails 3.0.7 app. How caan I use it?