SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
Glan Thomas
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
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
Luis Curo Salvatierra
 

Was ist angesagt? (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
 

Ähnlich wie CoffeeScript - A Rubyist's Love Affair

Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
ccherubino
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
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
Jarod Ferguson
 

Ähnlich wie 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
 

Mehr von Mark

Mehr von 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
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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

Hinweis der Redaktion

  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