SlideShare una empresa de Scribd logo
1 de 44
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

Más contenido relacionado

La actualidad más candente

50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim 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 LithiumNate Abele
 
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 HobgoblinsRoss 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 TestingPython Ireland
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcionalNSCoder Mexico
 
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 FrameworksNate Abele
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeJo Cranford
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo 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 / underscoreNicolas Carlo
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 

La actualidad más candente (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 a CoffeeScript - A Rubyist's Love Affair

Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
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 FunctionsOluwaleke Fakorede
 
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 IntroductionDmitry Sheiko
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid 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 JavaScriptGuy Royse
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan 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 PythonSiddhi
 
Rails 2010 Workshop
Rails 2010 WorkshopRails 2010 Workshop
Rails 2010 Workshopdtsadok
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovGeorgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScriptInnovecs
 

Similar a 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
 

Más de Mark

Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web AppsMark
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the RubyistMark
 
Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePointMark
 
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.jsMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
GET /better
GET /betterGET /better
GET /betterMark
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptMark
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptMark
 
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 ItMark
 
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 RubyistMark
 
RubyMotion
RubyMotionRubyMotion
RubyMotionMark
 
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 ChaiMark
 
CoffeeScript for the Rubyist
CoffeeScript for the RubyistCoffeeScript for the Rubyist
CoffeeScript for the RubyistMark
 
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 JasmineMark
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and RindaMark
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Mark
 

Más de 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
 

Último

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

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

Notas del editor

  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