SlideShare a Scribd company logo
CoffeeScript
A Rubyist’s Love Affair
Mark Bates
Ruby/Rails
Consultant
Author of
“Distributed
Programming with
Ruby”
“Insert Book Name
       Here”
What CoffeeScript is
       not!
No Just “Lack of
 Punctuation!
NOT RJS!!!
RJS Example
page.replace_html('tasks-completed',
Task.completed_count)
page.replace_html('tasks-remaining',
Task.remaining_count)
page.replace_html('task-status-' + @task.id.to_s,
@task.status.description)
page.visual_effect(:highlight, 'task-item-' +
@task.id.to_s, :duration => 1.0)
So what is
CoffeeScript?
CoffeeScript is...
“a little language that compiles into
JavaScript”
Easier to read and write
A hybrid of Ruby and Python
Helpful
So why should I
embrace (and love)
  CoffeeScript?
String Interpolation

     name = 'Mark'
     "Hello #{name}"
var name;
name = 'Mark';
"Hello " + name;
Heredoc
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>
"""
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>";
Ranges
# 1, 2, 3, 4, 5
[1..5]

# 1,..., 4
[1...5]

#1,...,500
[1..500]

#5, 4, 3, 2, 1
[5..1]

#500,...,1
[500..1]
var _i, _j, _results, _results2;
[1, 2, 3, 4, 5];
[1, 2, 3, 4];
(function() {
  _results = [];
  for (_i = 1; _i <= 500; _i++)
{ _results.push(_i); }
  return _results;
}).apply(this, arguments);
[5, 4, 3, 2, 1];
(function() {
  _results2 = [];
  for (_j = 500; _j >= 1; _j--)
{ _results2.push(_j); }
  return _results2;
}).apply(this, arguments);
Ruby Style
    Conditionals

Unless
In-line Conditionals
Conditionals
unless a
  console.log "a is false"

console.log "a is false" unless a
if (!a) {
  console.log("a is false");
}
if (!a) {
  console.log("a is false");
}
Functions

Bound Functions
Default Arguments
Splatted Arguments
Regular Functions
p = (name)->
  console.log "hello: #{name}"

p 'mark'
var p;
p = function(name) {
   return console.log("hello: " + name);
};
p('mark');
Regular Functions
p = (name)->
  console.log "hello: #{name}"

p 'mark'
Regular Functions
p = (name)->
  console.log "hello: #{name}"
                                 CoffeeScript
p 'mark'




p = ->(name) {
  puts "hello: #{name}"
}
                                 Ruby 1.9
p.call 'mark'
Bound Functions
   class Person

     def initialize(name)
       @name = name
     end

     def bind
       binding
     end

   end

   p = Person.new('mark')
   eval "puts @name", p.bind
Bound Functions
fetchData: =>
  url = "http://search.twitter.com/search.json?
q=#{encodeURIComponent(@hash_tag)}&rpp=#{@max_results}&callba
ck=?"
  $.get url, {}, @handleData, 'json'

handleData: (data) =>
  if data['error']?
    @handleError()
  if data.results.length is 0 and @fall_back
    @handleEmptyData()
  else if data.results.length > 0
    setTimeout (=> @fetchData()), 10000
    @render data
var __bind = function(fn, me){ return function(){ return fn.apply(me,
arguments); }; };
({
   fetchData: __bind(function() {
     var url;
     url = "http://search.twitter.com/search.json?q=" +
(encodeURIComponent(this.hash_tag)) + "&rpp=" + this.max_results + "&callback=?";
     return $.get(url, {}, this.handleData, 'json');
   }, this),
   handleData: __bind(function(data) {
     if (data['error'] != null) {
       this.handleError();
     }
     if (data.results.length === 0 && this.fall_back) {
       return this.handleEmptyData();
     } else if (data.results.length > 0) {
       setTimeout((__bind(function() {
         return this.fetchData();
       }, this)), 10000);
       return this.render(data);
     }
   }, this)
});
Default Arguments
createElement: (name, attributes = {}) ->
  obj = document.createElement name
  for key, val of attributes
    obj.setAttribute key, val
  obj
({
  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;
  }
});
Splatted Arguments
splatter = (first, second, others...) ->
  console.log "First: #{first}"
  console.log "Second: #{second}"
  console.log "Others: #{others.join(', ')}"

splatter [1..5]...
var splatter;
var __slice = Array.prototype.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]);
Array Loop
arr = [1..5]

for num in arr
  console.log num
var arr, num, _i, _len;
arr = [1, 2, 3, 4, 5];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
  num = arr[_i];
  console.log(num);
}
Hash Loop
for key, val of attributes
  console.log "key: #{key}"
  console.log "val: #{val}"
var key, val;
for (key in attributes) {
  val = attributes[key];
  console.log("key: " + key);
  console.log("val: " + val);
}
Classes

Easy To Define
Easy To Extend
Keep Code Clean
Classes
class Employee

  constructor: (@name, @options = {})->

  job: ->
    @options.job

mark = new Employee('Mark', job: 'Developer')

mark.job() # => 'Developer'
mark.name # => 'Mark'
var Employee, mark;
Employee = (function() {
  function Employee(name, options) {
     this.name = name;
     this.options = options != null ? options : {};
  }
  Employee.prototype.job = function() {
     return this.options.job;
  };
  return Employee;
})();
mark = new Employee('Mark', {
  job: 'Developer'
});
mark.job();
mark.name;
Extending Classes
class Manager extends Employee

  job: ->
    "$$$ #{super}"

steve = new Manager('Steve', job: 'CEO')

steve.job() # => '$$$ CEO'
steve.name # => 'Steve'
var Manager, steve;
var __hasProp = Object.prototype.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() {
   __extends(Manager, Employee);
   function Manager() {
      Manager.__super__.constructor.apply(this, arguments);
   }
   Manager.prototype.job = function() {
      return "$$$ " + Manager.__super__.job.apply(this, arguments);
   };
   return Manager;
})();
steve = new Manager('Steve', {
   job: 'CEO'
});
steve.job();
steve.name;
@
class User

  constructor: (@name)->
    @new_record = true

  @find: (id)->
    # do some work
@
class User

  constructor: (name)->
    @name = name
    @new_record = true

  @find: (id)->
    # do some work
var User;
User = (function() {
  function User(name) {
    this.name = name;
    this.new_record = true;
  }
  User.find = function(id) {};
  return User;
})();
Thank You
        @markbates
http://www.markbates.com

More Related Content

What's hot

50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For MobileGlan Thomas
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
Łukasz Langa
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
Ross Tuck
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
zfconfua
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
NSCoder Mexico
 
Lodash js
Lodash jsLodash js
Lodash js
LearningTech
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
Luc Bors
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is Awesome
Jo Cranford
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
Gaetano Causio
 

What's hot (20)

50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
Lodash js
Lodash jsLodash js
Lodash js
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is Awesome
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 

Similar to CoffeeScript - A Rubyist's Love Affair

Why ruby
Why rubyWhy ruby
Why ruby
rstankov
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
niklal
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Scott Leberknight
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015qmmr
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
Rails 2010 Workshop
Rails 2010 WorkshopRails 2010 Workshop
Rails 2010 Workshop
dtsadok
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
Georgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
Innovecs
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
Demian Holderegger
 

Similar to CoffeeScript - A Rubyist's Love Affair (20)

Why ruby
Why rubyWhy ruby
Why ruby
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
All you need to know about JavaScript Functions
All you need to know about JavaScript FunctionsAll you need to know about JavaScript Functions
All you need to know about JavaScript Functions
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Javascript
JavascriptJavascript
Javascript
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Rails 2010 Workshop
Rails 2010 WorkshopRails 2010 Workshop
Rails 2010 Workshop
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 

More from Mark

Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
Mark
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
Mark
 
Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the Rubyist
Mark
 
Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePoint
Mark
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
Mark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
Mark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
Mark
 
GET /better
GET /betterGET /better
GET /better
Mark
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Mark
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScript
Mark
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing It
Mark
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(
Mark
 
CoffeeScript for the Rubyist
CoffeeScript for the RubyistCoffeeScript for the Rubyist
CoffeeScript for the Rubyist
Mark
 
RubyMotion
RubyMotionRubyMotion
RubyMotion
Mark
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and Chai
Mark
 
CoffeeScript for the Rubyist
CoffeeScript for the RubyistCoffeeScript for the Rubyist
CoffeeScript for the Rubyist
Mark
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with Jasmine
Mark
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and Rinda
Mark
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010
Mark
 

More from Mark (19)

Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the Rubyist
 
Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePoint
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
GET /better
GET /betterGET /better
GET /better
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScript
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing It
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(
 
CoffeeScript for the Rubyist
CoffeeScript for the RubyistCoffeeScript for the Rubyist
CoffeeScript for the Rubyist
 
RubyMotion
RubyMotionRubyMotion
RubyMotion
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and Chai
 
CoffeeScript for the Rubyist
CoffeeScript for the RubyistCoffeeScript for the Rubyist
CoffeeScript for the Rubyist
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with Jasmine
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and Rinda
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010
 

Recently uploaded

Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

CoffeeScript - A Rubyist's Love Affair

  • 5. No Just “Lack of Punctuation!
  • 7. RJS Example page.replace_html('tasks-completed', Task.completed_count) page.replace_html('tasks-remaining', Task.remaining_count) page.replace_html('task-status-' + @task.id.to_s, @task.status.description) page.visual_effect(:highlight, 'task-item-' + @task.id.to_s, :duration => 1.0)
  • 9. CoffeeScript is... “a little language that compiles into JavaScript” Easier to read and write A hybrid of Ruby and Python Helpful
  • 10. So why should I embrace (and love) CoffeeScript?
  • 11. String Interpolation name = 'Mark' "Hello #{name}"
  • 12. var name; name = 'Mark'; "Hello " + name;
  • 13. Heredoc 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> """
  • 14. 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>";
  • 15. Ranges # 1, 2, 3, 4, 5 [1..5] # 1,..., 4 [1...5] #1,...,500 [1..500] #5, 4, 3, 2, 1 [5..1] #500,...,1 [500..1]
  • 16. var _i, _j, _results, _results2; [1, 2, 3, 4, 5]; [1, 2, 3, 4]; (function() { _results = []; for (_i = 1; _i <= 500; _i++) { _results.push(_i); } return _results; }).apply(this, arguments); [5, 4, 3, 2, 1]; (function() { _results2 = []; for (_j = 500; _j >= 1; _j--) { _results2.push(_j); } return _results2; }).apply(this, arguments);
  • 17. Ruby Style Conditionals Unless In-line Conditionals
  • 18. Conditionals unless a console.log "a is false" console.log "a is false" unless a
  • 19. if (!a) { console.log("a is false"); } if (!a) { console.log("a is false"); }
  • 21. Regular Functions p = (name)-> console.log "hello: #{name}" p 'mark'
  • 22. var p; p = function(name) { return console.log("hello: " + name); }; p('mark');
  • 23. Regular Functions p = (name)-> console.log "hello: #{name}" p 'mark'
  • 24. Regular Functions p = (name)-> console.log "hello: #{name}" CoffeeScript p 'mark' p = ->(name) { puts "hello: #{name}" } Ruby 1.9 p.call 'mark'
  • 25. Bound Functions class Person def initialize(name) @name = name end def bind binding end end p = Person.new('mark') eval "puts @name", p.bind
  • 26. Bound Functions fetchData: => url = "http://search.twitter.com/search.json? q=#{encodeURIComponent(@hash_tag)}&rpp=#{@max_results}&callba ck=?" $.get url, {}, @handleData, 'json' handleData: (data) => if data['error']? @handleError() if data.results.length is 0 and @fall_back @handleEmptyData() else if data.results.length > 0 setTimeout (=> @fetchData()), 10000 @render data
  • 27. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; ({ fetchData: __bind(function() { var url; url = "http://search.twitter.com/search.json?q=" + (encodeURIComponent(this.hash_tag)) + "&rpp=" + this.max_results + "&callback=?"; return $.get(url, {}, this.handleData, 'json'); }, this), handleData: __bind(function(data) { if (data['error'] != null) { this.handleError(); } if (data.results.length === 0 && this.fall_back) { return this.handleEmptyData(); } else if (data.results.length > 0) { setTimeout((__bind(function() { return this.fetchData(); }, this)), 10000); return this.render(data); } }, this) });
  • 28. Default Arguments createElement: (name, attributes = {}) -> obj = document.createElement name for key, val of attributes obj.setAttribute key, val obj
  • 29. ({ 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; } });
  • 30. Splatted Arguments splatter = (first, second, others...) -> console.log "First: #{first}" console.log "Second: #{second}" console.log "Others: #{others.join(', ')}" splatter [1..5]...
  • 31. var splatter; var __slice = Array.prototype.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]);
  • 32. Array Loop arr = [1..5] for num in arr console.log num
  • 33. var arr, num, _i, _len; arr = [1, 2, 3, 4, 5]; for (_i = 0, _len = arr.length; _i < _len; _i++) { num = arr[_i]; console.log(num); }
  • 34. Hash Loop for key, val of attributes console.log "key: #{key}" console.log "val: #{val}"
  • 35. var key, val; for (key in attributes) { val = attributes[key]; console.log("key: " + key); console.log("val: " + val); }
  • 36. Classes Easy To Define Easy To Extend Keep Code Clean
  • 37. Classes class Employee constructor: (@name, @options = {})-> job: -> @options.job mark = new Employee('Mark', job: 'Developer') mark.job() # => 'Developer' mark.name # => 'Mark'
  • 38. var Employee, mark; Employee = (function() { function Employee(name, options) { this.name = name; this.options = options != null ? options : {}; } Employee.prototype.job = function() { return this.options.job; }; return Employee; })(); mark = new Employee('Mark', { job: 'Developer' }); mark.job(); mark.name;
  • 39. Extending Classes class Manager extends Employee job: -> "$$$ #{super}" steve = new Manager('Steve', job: 'CEO') steve.job() # => '$$$ CEO' steve.name # => 'Steve'
  • 40. var Manager, steve; var __hasProp = Object.prototype.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() { __extends(Manager, Employee); function Manager() { Manager.__super__.constructor.apply(this, arguments); } Manager.prototype.job = function() { return "$$$ " + Manager.__super__.job.apply(this, arguments); }; return Manager; })(); steve = new Manager('Steve', { job: 'CEO' }); steve.job(); steve.name;
  • 41. @ class User constructor: (@name)-> @new_record = true @find: (id)-> # do some work
  • 42. @ class User constructor: (name)-> @name = name @new_record = true @find: (id)-> # do some work
  • 43. var User; User = (function() { function User(name) { this.name = name; this.new_record = true; } User.find = function(id) {}; return User; })();
  • 44. Thank You @markbates http://www.markbates.com

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n