Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
COFFEESCRIPT
   A Rubyist’s Love Affair
Mark Bates
Distributed
Programming
    with
    Ruby
     Addison-Wesley
          2009


http://books.markbates.com
Programming
      in
 CoffeeScript
      Addison-Wesley
           2012


 http://books.markbates.com
A (BRIEF) HISTORY LESSON
“
I need to come up with a scripting language
for web browsers.


    I know! I'll make it cool and Lispy!      ”
        ...
“   Yeah, So... Java is getting really popular.
    So we're going to need you to rewrite your
    language into something...
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.lik...
FAST FORWARD
    About 15 Years
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.lik...
class MyApp.Models.Product extends Backbone.Model

  isLiked: ->
    !@like()?.isNew()

  like: ->
    new MyApp.Models.Li...
WHAT IS COFFEESCRIPT?
What is CoffeeScript?
What is CoffeeScript?

“A little language that compiles into JavaScript.”
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
...
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
...
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
...
What CoffeeScript Is Not?


Not Magic!

Limited by what JavaScript can already do
“
I’m happy writing JavaScript.

I don’t need to learn another language.   ”
FINE WITH ME
BUT...
.MODEL SMALL                           DISP:
                                               MOV BL,VAL1
.STACK 64         ...
.MODEL SMALL                                      DISP:
                                       Assembly           MOV BL,V...
#include <stdio.h>            C
int fibonacci()
{
  int n = 100;
  int a = 0;
  int b = 1;
  int sum;
  int i;

    for (i...
public static void fibonacci() {    Java
  int n = 100;
  int a = 0;
  int b = 1;

    for (int i = 0; i < n; i++) {
     ...
def fibonacci           Ruby
  a = 0
  b = 1

  100.times do
    printf("%dn", a)
    a, b = b, a + b
  end

end
“
I can write an app just as well in Java

as I can in Ruby, but damn it if Ruby


isn’t nicer to read and write!   ”
SAME GOES FOR
COFFEESCRIPT
SYNTAX
$(function() {                             $ ->
                                             success = (data) ->
  success...
Syntax Rules

No semi-colons (ever!)

No curly braces*

No ‘function’ keyword

Relaxed parentheses

Whitespace significant...
Parentheses Rules
# Not required without arguments:
noArg1 = ->
  # do something

# Not required without arguments:
noArg2...
Parentheses Rules
var noArg1, noArg2, withArg;

noArg1 = function() {};

noArg2 = function() {};

withArg = function(arg) ...
Parentheses Rules
# Bad:
$ "#some_id" .text()
# $("#some_id".text());

# Good:
$("#some_id").text()
# $("#some_id").text();
Whitespace
Whitespace
$(function() {
success = function(data) {
if (data.errors != null) {
alert("There was an error!");
} else {
$("...
Whitespace
$(function() {                      def fibonacci
success = function(data) {          a = 0
if (data.errors != ...
Whitespace
$(function() {                             def fibonacci
                                             a = 0
  s...
Whitespace
$ ->
  success = (data) ->
     if data.errors?
       alert "There was an error!"
     else
       $("#content...
Whitespace
$(function() {
  var success;
  success = function(data) {
     if (data.errors != null) {
       return alert(...
RUBYSCRIPT?
Conditionals
Conditionals
if true
  doSomething()

unless true
  doSomething()
Conditionals
if true                doSomething() if true
  doSomething()
                       doSomething() unless true...
Conditionals
if true                    doSomething() if true
  doSomething()
                           doSomething() unl...
Objects/Hashes
someObject = {conf: "RailsConf", talk: "CoffeeScript"}

someObject =
  conf: "RailsConf"
  talk: "CoffeeScr...
Objects/Hashes
var someObject;

someObject = {
   conf: "RailsConf",
   talk: "CoffeeScript"
};

someObject = {
   conf: "...
Ranges
a = [1..5]

b = [1...5]

c = [1..100]

d = [100..1]
Ranges
a = [1..5]     var a, b, c, d, _i, _j, _results, _results1;

               a = [1, 2, 3, 4, 5];
b = [1...5]
      ...
String Interpolation
name = "RailsConf 2012"

console.log "Hello #{name}"
# Hello RailsConf 2012

console.log 'Hello #{nam...
String Interpolation
name = "RailsConf 2012"       var name;

console.log "Hello #{name}"   name = "RailsConf 2012";
# Hel...
Heredocs
html = """
  <div class="comment" id="tweet-#{tweet.id_str}">
    <hr>
    <div class='tweet'>
      <span class=...
Heredocs
var html;

html = "<div class="comment" id="tweet-" + tweet.id_str
+ "">n <hr>n <div class='tweet'>n      <span c...
Functions
p = (name) ->
  console.log "Hello #{name}"

p('RailsConf 2012')
Functions
var p;

p = function(name) {
   return console.log("Hello " + name);
};

p('RailsConf 2012');
Functions
p = (name)->
  console.log "Hello #{name}"

p('RailsConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"     CoffeeScript
p('RailsConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"     CoffeeScript
p('RailsConf 2012')




p = ->(name) {
  puts "Hello...
Default Arguments
createElement = (name, attributes = {}) ->
  obj = document.createElement name
  for key, val of attribu...
Default Arguments
var createElement;

createElement = function(name, attributes) {
   var key, obj, val;
   if (attributes...
Splats*
splatter = (first, second, others...) ->
  console.log "First: #{first}"
  console.log "Second: #{second}"
  conso...
Splats*
var splatter,
  __slice = [].slice;

splatter = function() {
   var first, others, second;
   first = arguments[0]...
Loops & Comprehensions
for someName in someArray
  console.log someName

for key, value of someObject
  console.log "#{key...
Loops & Comprehensions
var key, someName, value, _i, _len;

for (_i = 0, _len = someArray.length; _i < _len; _i++) {
  som...
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i ...
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers when number <= 3
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i ...
Loops & Comprehensions
numbers = [1, 2, 3, 4, 5]

low_numbers = (number * 2 for number in numbers when number <= 3)

conso...
Loops & Comprehensions
var low_numbers, number, numbers;

numbers = [1, 2, 3, 4, 5];

low_numbers = (function() {
  var _i...
Classes
class Employee

emp = new Employee()
emp.firstName = "Mark"
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee() {}

  return Em...
Classes
class Employee

  constructor: (@options = {}) ->

  salary: ->
    @options.salary ?= "$250,000"

emp = new Emplo...
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee(options) {
    th...
Extending Classes
class Manager extends Employee

  constructor: ->
    super
    @options.salary ?= "$500,000"

manager =...
Extending Classes
var Manager, manager,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var ...
Extending Classes
class Manager extends Employee

  constructor: ->
    super
    @options.salary ?= "$500,000"

  salary:...
Extending Classes
var Manager, manager,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var ...
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')...
Bound Functions
about to execute callback...
Hello undefined
...executed callback
about to execute callback...
Hello undef...
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')...
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')...
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"

bob = new User('bob')...
Bound Functions
about to execute callback...
Hello bob
...executed callback
about to execute callback...
Hello mary
...exe...
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"
Bound Functions
var User,
  __bind = function(fn, me){ return function(){ return fn.apply(me,
arguments); }; };

User = (f...
FINALLY
One of my favorite features
Existential Operator
if foo?
  console.log "foo"

console.log "foo" if foo?
Existential Operator
if (typeof foo !== "undefined" && foo !== null) {
  console.log("foo");
}

if (typeof foo !== "undefi...
WAIT! IT GETS BETTER!
Existential Operator
console?.log "foo"
Existential Operator
console?.log "foo"




if (typeof console !== "undefined" && console !== null) {
  console.log("foo")...
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName




if ((typeof currentUser !== "undef...
What Didn’t I Cover?
Scoping

Security

Strict Mode

Fixes common ‘mistakes’

Operators

The `do` keyword

Plenty more!
Thank You
Thank You
myName = "Mark Bates"

you.should buyBook("Programming in CoffeeScript")
 .at("http://books.markbates.com")

you...
CoffeeScript for the Rubyist
CoffeeScript for the Rubyist
CoffeeScript for the Rubyist
Upcoming SlideShare
Loading in …5
×

of

CoffeeScript for the Rubyist Slide 1 CoffeeScript for the Rubyist Slide 2 CoffeeScript for the Rubyist Slide 3 CoffeeScript for the Rubyist Slide 4 CoffeeScript for the Rubyist Slide 5 CoffeeScript for the Rubyist Slide 6 CoffeeScript for the Rubyist Slide 7 CoffeeScript for the Rubyist Slide 8 CoffeeScript for the Rubyist Slide 9 CoffeeScript for the Rubyist Slide 10 CoffeeScript for the Rubyist Slide 11 CoffeeScript for the Rubyist Slide 12 CoffeeScript for the Rubyist Slide 13 CoffeeScript for the Rubyist Slide 14 CoffeeScript for the Rubyist Slide 15 CoffeeScript for the Rubyist Slide 16 CoffeeScript for the Rubyist Slide 17 CoffeeScript for the Rubyist Slide 18 CoffeeScript for the Rubyist Slide 19 CoffeeScript for the Rubyist Slide 20 CoffeeScript for the Rubyist Slide 21 CoffeeScript for the Rubyist Slide 22 CoffeeScript for the Rubyist Slide 23 CoffeeScript for the Rubyist Slide 24 CoffeeScript for the Rubyist Slide 25 CoffeeScript for the Rubyist Slide 26 CoffeeScript for the Rubyist Slide 27 CoffeeScript for the Rubyist Slide 28 CoffeeScript for the Rubyist Slide 29 CoffeeScript for the Rubyist Slide 30 CoffeeScript for the Rubyist Slide 31 CoffeeScript for the Rubyist Slide 32 CoffeeScript for the Rubyist Slide 33 CoffeeScript for the Rubyist Slide 34 CoffeeScript for the Rubyist Slide 35 CoffeeScript for the Rubyist Slide 36 CoffeeScript for the Rubyist Slide 37 CoffeeScript for the Rubyist Slide 38 CoffeeScript for the Rubyist Slide 39 CoffeeScript for the Rubyist Slide 40 CoffeeScript for the Rubyist Slide 41 CoffeeScript for the Rubyist Slide 42 CoffeeScript for the Rubyist Slide 43 CoffeeScript for the Rubyist Slide 44 CoffeeScript for the Rubyist Slide 45 CoffeeScript for the Rubyist Slide 46 CoffeeScript for the Rubyist Slide 47 CoffeeScript for the Rubyist Slide 48 CoffeeScript for the Rubyist Slide 49 CoffeeScript for the Rubyist Slide 50 CoffeeScript for the Rubyist Slide 51 CoffeeScript for the Rubyist Slide 52 CoffeeScript for the Rubyist Slide 53 CoffeeScript for the Rubyist Slide 54 CoffeeScript for the Rubyist Slide 55 CoffeeScript for the Rubyist Slide 56 CoffeeScript for the Rubyist Slide 57 CoffeeScript for the Rubyist Slide 58 CoffeeScript for the Rubyist Slide 59 CoffeeScript for the Rubyist Slide 60 CoffeeScript for the Rubyist Slide 61 CoffeeScript for the Rubyist Slide 62 CoffeeScript for the Rubyist Slide 63 CoffeeScript for the Rubyist Slide 64 CoffeeScript for the Rubyist Slide 65 CoffeeScript for the Rubyist Slide 66 CoffeeScript for the Rubyist Slide 67 CoffeeScript for the Rubyist Slide 68 CoffeeScript for the Rubyist Slide 69 CoffeeScript for the Rubyist Slide 70 CoffeeScript for the Rubyist Slide 71 CoffeeScript for the Rubyist Slide 72 CoffeeScript for the Rubyist Slide 73 CoffeeScript for the Rubyist Slide 74 CoffeeScript for the Rubyist Slide 75 CoffeeScript for the Rubyist Slide 76 CoffeeScript for the Rubyist Slide 77 CoffeeScript for the Rubyist Slide 78 CoffeeScript for the Rubyist Slide 79 CoffeeScript for the Rubyist Slide 80 CoffeeScript for the Rubyist Slide 81 CoffeeScript for the Rubyist Slide 82 CoffeeScript for the Rubyist Slide 83 CoffeeScript for the Rubyist Slide 84 CoffeeScript for the Rubyist Slide 85 CoffeeScript for the Rubyist Slide 86 CoffeeScript for the Rubyist Slide 87 CoffeeScript for the Rubyist Slide 88 CoffeeScript for the Rubyist Slide 89 CoffeeScript for the Rubyist Slide 90 CoffeeScript for the Rubyist Slide 91 CoffeeScript for the Rubyist Slide 92 CoffeeScript for the Rubyist Slide 93 CoffeeScript for the Rubyist Slide 94 CoffeeScript for the Rubyist Slide 95 CoffeeScript for the Rubyist Slide 96 CoffeeScript for the Rubyist Slide 97 CoffeeScript for the Rubyist Slide 98 CoffeeScript for the Rubyist Slide 99 CoffeeScript for the Rubyist Slide 100 CoffeeScript for the Rubyist Slide 101
Upcoming SlideShare
Complex Made Simple: Sleep Better With TorqueBox
Next
Download to read offline and view in fullscreen.

7 Likes

Share

Download to read offline

CoffeeScript for the Rubyist

Download to read offline

Presented at RailsConf 2012 on April 23rd, 2012. This talk is an intro to the CoffeeScript language from a Rubyists perspective.

Related Books

Free with a 30 day trial from Scribd

See all

CoffeeScript for the Rubyist

  1. COFFEESCRIPT A Rubyist’s Love Affair
  2. Mark Bates
  3. Distributed Programming with Ruby Addison-Wesley 2009 http://books.markbates.com
  4. Programming in CoffeeScript Addison-Wesley 2012 http://books.markbates.com
  5. A (BRIEF) HISTORY LESSON
  6. “ I need to come up with a scripting language for web browsers. I know! I'll make it cool and Lispy! ” Dramatic Re-enactment (1995)
  7. “ Yeah, So... Java is getting really popular. So we're going to need you to rewrite your language into something a bit more Java- esque and name it something like JavaScript.   Yeah, and we're going to need it in a week. Thanks, that'd be great. ” Dramatic Re-enactment (1995)
  8. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  9. FAST FORWARD About 15 Years
  10. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  11. class MyApp.Models.Product extends Backbone.Model isLiked: -> !@like()?.isNew() like: -> new MyApp.Models.Like(@get("like")) image: (size = "full") -> if @get("image")? img = @get("image")[size] unless img? img = "/images/fallback/product_#{size}_default.png" return img
  12. WHAT IS COFFEESCRIPT?
  13. What is CoffeeScript?
  14. What is CoffeeScript? “A little language that compiles into JavaScript.”
  15. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript
  16. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc...
  17. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python.
  18. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python. Helpful.
  19. What CoffeeScript Is Not? Not Magic! Limited by what JavaScript can already do
  20. “ I’m happy writing JavaScript. I don’t need to learn another language. ”
  21. FINE WITH ME
  22. BUT...
  23. .MODEL SMALL DISP: MOV BL,VAL1 .STACK 64 ADD BL,VAL2 .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  24. .MODEL SMALL DISP: Assembly MOV BL,VAL1 .STACK 64 ADD BL,VAL2 .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  25. #include <stdio.h> C int fibonacci() { int n = 100; int a = 0; int b = 1; int sum; int i; for (i = 0; i < n; i++) { printf("%dn", a); sum = a + b; a = b; b = sum; } return 0; }
  26. public static void fibonacci() { Java int n = 100; int a = 0; int b = 1; for (int i = 0; i < n; i++) { System.out.println(a); a = a + b; b = a - b; } }
  27. def fibonacci Ruby a = 0 b = 1 100.times do printf("%dn", a) a, b = b, a + b end end
  28. “ I can write an app just as well in Java as I can in Ruby, but damn it if Ruby isn’t nicer to read and write! ”
  29. SAME GOES FOR COFFEESCRIPT
  30. SYNTAX
  31. $(function() { $ -> success = (data) -> success = function(data) { if data.errors? if (data.errors != null) { alert "There was an error!" alert("There was an error!"); else } else { $("#content").text(data.message) $("#content").text(data.message); } $.get('/users', success, 'json') }; $.get('/users', success, 'json'); }); JavaScript CoffeeScript
  32. Syntax Rules No semi-colons (ever!) No curly braces* No ‘function’ keyword Relaxed parentheses Whitespace significant formatting
  33. Parentheses Rules # Not required without arguments: noArg1 = -> # do something # Not required without arguments: noArg2 = () -> # do something # Required without arguments: # Required with Arguments: noArg1() withArg = (arg) -> noArg2() # do something # Not required with arguments: withArg("bar") withArg "bar"
  34. Parentheses Rules var noArg1, noArg2, withArg; noArg1 = function() {}; noArg2 = function() {}; withArg = function(arg) {}; noArg1(); noArg2(); withArg("bar"); withArg("bar");
  35. Parentheses Rules # Bad: $ "#some_id" .text() # $("#some_id".text()); # Good: $("#some_id").text() # $("#some_id").text();
  36. Whitespace
  37. Whitespace $(function() { success = function(data) { if (data.errors != null) { alert("There was an error!"); } else { $("#content").text(data.message); } }; $.get('/users', success, 'json'); });
  38. Whitespace $(function() { def fibonacci success = function(data) { a = 0 if (data.errors != null) { b = 1 alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  39. Whitespace $(function() { def fibonacci a = 0 success = function(data) { b = 1 if (data.errors != null) { alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  40. Whitespace $ -> success = (data) -> if data.errors? alert "There was an error!" else $("#content").text(data.message) $.get('/users', success, 'json')
  41. Whitespace $(function() { var success; success = function(data) { if (data.errors != null) { return alert("There was an error!"); } else { return $("#content").text(data.message); } }; return $.get('/users', success, 'json'); });
  42. RUBYSCRIPT?
  43. Conditionals
  44. Conditionals if true doSomething() unless true doSomething()
  45. Conditionals if true doSomething() if true doSomething() doSomething() unless true unless true doSomething()
  46. Conditionals if true doSomething() if true doSomething() doSomething() unless true unless true doSomething() if true doSomething() else doSomethingElse()
  47. Objects/Hashes someObject = {conf: "RailsConf", talk: "CoffeeScript"} someObject = conf: "RailsConf" talk: "CoffeeScript" someFunction(conf: "RailsConf", talk: "CoffeeScript")
  48. Objects/Hashes var someObject; someObject = { conf: "RailsConf", talk: "CoffeeScript" }; someObject = { conf: "RailsConf", talk: "CoffeeScript" }; someFunction({ conf: "RailsConf", talk: "CoffeeScript" });
  49. Ranges a = [1..5] b = [1...5] c = [1..100] d = [100..1]
  50. Ranges a = [1..5] var a, b, c, d, _i, _j, _results, _results1; a = [1, 2, 3, 4, 5]; b = [1...5] b = [1, 2, 3, 4]; c = [1..100] c = (function() { _results = []; d = [100..1] for (_i = 1; _i <= 100; _i++){ _results.push(_i); } return _results; }).apply(this); d = (function() { _results1 = []; for (_j = 100; _j >= 1; _j--){ _results1.push(_j); } return _results1; }).apply(this);
  51. String Interpolation name = "RailsConf 2012" console.log "Hello #{name}" # Hello RailsConf 2012 console.log 'Hello #{name}' # Hello #{name}
  52. String Interpolation name = "RailsConf 2012" var name; console.log "Hello #{name}" name = "RailsConf 2012"; # Hello RailsConf 2012 console.log("Hello " + name); console.log 'Hello #{name}' # Hello #{name} console.log('Hello #{name}');
  53. Heredocs html = """ <div class="comment" id="tweet-#{tweet.id_str}"> <hr> <div class='tweet'> <span class="imgr"><img src="#{tweet.profile_image_url}"></span> <span class="txtr"> <h5><a href="http://twitter.com/#{tweet.from_user}" target="_blank">@#{tweet.from_user}</a></h5> <p>#{tweet.text}</p> <p class="comment-posted-on">#{tweet.created_at}</p> </span> </div> </div> """
  54. Heredocs var html; html = "<div class="comment" id="tweet-" + tweet.id_str + "">n <hr>n <div class='tweet'>n <span class= "imgr"><img src="" + tweet.profile_image_url + ""></ span>n <span class="txtr">n <h5><a href= "http://twitter.com/" + tweet.from_user + "" target= "_blank">@" + tweet.from_user + "</a></h5>n <p>" + tweet.text + "</p>n <p class="comment-posted-on">" + tweet.created_at + "</p>n </span>n </div>n</div>";
  55. Functions p = (name) -> console.log "Hello #{name}" p('RailsConf 2012')
  56. Functions var p; p = function(name) { return console.log("Hello " + name); }; p('RailsConf 2012');
  57. Functions p = (name)-> console.log "Hello #{name}" p('RailsConf 2012')
  58. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('RailsConf 2012')
  59. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('RailsConf 2012') p = ->(name) { puts "Hello #{name}" } Ruby 1.9 p.call('RailsConf 2012')
  60. Default Arguments createElement = (name, attributes = {}) -> obj = document.createElement name for key, val of attributes obj.setAttribute key, val obj
  61. Default Arguments var createElement; createElement = function(name, attributes) { var key, obj, val; if (attributes == null) { attributes = {}; } obj = document.createElement(name); for (key in attributes) { val = attributes[key]; obj.setAttribute(key, val); } return obj; };
  62. Splats* splatter = (first, second, others...) -> console.log "First: #{first}" console.log "Second: #{second}" console.log "Others: #{others.join(', ')}" splatter [1..5]...
  63. Splats* var splatter, __slice = [].slice; splatter = function() { var first, others, second; first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : []; console.log("First: " + first); console.log("Second: " + second); return console.log("Others: " + (others.join(', '))); }; splatter.apply(null, [1, 2, 3, 4, 5]);
  64. Loops & Comprehensions for someName in someArray console.log someName for key, value of someObject console.log "#{key}: #{value}"
  65. Loops & Comprehensions var key, someName, value, _i, _len; for (_i = 0, _len = someArray.length; _i < _len; _i++) { someName = someArray[_i]; console.log(someName); } for (key in someObject) { value = someObject[key]; console.log("" + key + ": " + value); }
  66. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers
  67. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; console.log(number); }
  68. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers when number <= 3
  69. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { console.log(number); } }
  70. Loops & Comprehensions numbers = [1, 2, 3, 4, 5] low_numbers = (number * 2 for number in numbers when number <= 3) console.log low_numbers # [ 2, 4, 6 ]
  71. Loops & Comprehensions var low_numbers, number, numbers; numbers = [1, 2, 3, 4, 5]; low_numbers = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { _results.push(number * 2); } } return _results; })(); console.log(low_numbers);
  72. Classes class Employee emp = new Employee() emp.firstName = "Mark"
  73. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee() {} return Employee; })(); emp = new Employee(); emp.firstName = "Mark";
  74. Classes class Employee constructor: (@options = {}) -> salary: -> @options.salary ?= "$250,000" emp = new Employee() console.log emp.salary() # "$250,000" emp = new Employee(salary: "$100,000") console.log emp.salary() # "$100,000"
  75. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee(options) { this.options = options != null ? options : {}; } Employee.prototype.salary = function() { var _base, _ref; return (_ref = (_base = this.options).salary) != null ? _ref : _base.salary = "$250,000"; }; return Employee; })(); emp = new Employee(); console.log(emp.salary()); emp = new Employee({ salary: "$100,000" }); console.log(emp.salary());
  76. Extending Classes class Manager extends Employee constructor: -> super @options.salary ?= "$500,000" manager = new Manager() console.log manager.salary() # "$500,000"
  77. Extending Classes var Manager, manager, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Manager = (function(_super) { __extends(Manager, _super); Manager.name = 'Manager'; function Manager() { var _base; Manager.__super__.constructor.apply(this, arguments); if ((_base = this.options).salary == null) { _base.salary = "$500,000"; } } return Manager; })(Employee); manager = new Manager(); console.log(manager.salary());
  78. Extending Classes class Manager extends Employee constructor: -> super @options.salary ?= "$500,000" salary: -> "#{super} + $10k" manager = new Manager() console.log manager.salary() # "$500,000 + $10k"
  79. Extending Classes var Manager, manager, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Manager = (function(_super) { __extends(Manager, _super); Manager.name = 'Manager'; function Manager() { var _base; Manager.__super__.constructor.apply(this, arguments); if ((_base = this.options).salary == null) { _base.salary = "$500,000"; } } Manager.prototype.salary = function() { return "" + Manager.__super__.salary.apply(this, arguments) + " + $10k"; }; return Manager; })(Employee); manager = new Manager(); console.log(manager.salary());
  80. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  81. Bound Functions about to execute callback... Hello undefined ...executed callback about to execute callback... Hello undefined ...executed callback
  82. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  83. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  84. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  85. Bound Functions about to execute callback... Hello bob ...executed callback about to execute callback... Hello mary ...executed callback
  86. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}"
  87. Bound Functions var User, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; User = (function() { User.name = 'User'; function User(name) { this.name = name; this.sayHi = __bind(this.sayHi, this); } User.prototype.sayHi = function() { return console.log("Hello " + this.name); }; return User; })();
  88. FINALLY One of my favorite features
  89. Existential Operator if foo? console.log "foo" console.log "foo" if foo?
  90. Existential Operator if (typeof foo !== "undefined" && foo !== null) { console.log("foo"); } if (typeof foo !== "undefined" && foo !== null) { console.log("foo"); }
  91. WAIT! IT GETS BETTER!
  92. Existential Operator console?.log "foo"
  93. Existential Operator console?.log "foo" if (typeof console !== "undefined" && console !== null) { console.log("foo"); }
  94. Existential Operator if currentUser?.firstName? console.log currentUser.firstName
  95. Existential Operator if currentUser?.firstName? console.log currentUser.firstName if ((typeof currentUser !== "undefined" && currentUser !== null ? currentUser.firstName : void 0) != null) { console.log(currentUser.firstName); }
  96. What Didn’t I Cover? Scoping Security Strict Mode Fixes common ‘mistakes’ Operators The `do` keyword Plenty more!
  97. Thank You
  98. Thank You myName = "Mark Bates" you.should buyBook("Programming in CoffeeScript") .at("http://books.markbates.com") you.should followMe(@markbates)
  • huang900107

    Aug. 31, 2012
  • zentrification

    Jul. 15, 2012
  • collegeimprovements

    Jun. 26, 2012
  • newobject

    May. 11, 2012
  • kevinj

    May. 2, 2012
  • germanlinux

    Apr. 27, 2012
  • rgaidot

    Apr. 26, 2012

Presented at RailsConf 2012 on April 23rd, 2012. This talk is an intro to the CoffeeScript language from a Rubyists perspective.

Views

Total views

15,103

On Slideshare

0

From embeds

0

Number of embeds

1,015

Actions

Downloads

68

Shares

0

Comments

0

Likes

7

×