CoffeeScript - A Rubyist's Love Affair
Upcoming SlideShare
Loading in...5
×
 

CoffeeScript - A Rubyist's Love Affair

on

  • 3,866 views

Presented on 8/9/2011 to the Boston Ruby User's Group, this presentation talks about certain aspects of CoffeeScript and how it relates to Ruby.

Presented on 8/9/2011 to the Boston Ruby User's Group, this presentation talks about certain aspects of CoffeeScript and how it relates to Ruby.

Statistics

Views

Total Views
3,866
Views on SlideShare
3,850
Embed Views
16

Actions

Likes
6
Downloads
42
Comments
0

5 Embeds 16

http://twitter.com 7
https://twitter.com 5
http://us-w1.rockmelt.com 2
http://www.hanrss.com 1
http://a0.twimg.com 1

Accessibility

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

CoffeeScript - A Rubyist's Love Affair CoffeeScript - A Rubyist's Love Affair Presentation Transcript

  • CoffeeScriptA Rubyist’s Love Affair
  • Mark BatesRuby/RailsConsultantAuthor of“DistributedProgramming withRuby”
  • “Insert Book Name Here”
  • What CoffeeScript is not!
  • No Just “Lack of Punctuation!
  • NOT RJS!!!
  • RJS Examplepage.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 isCoffeeScript?
  • CoffeeScript is...“a little language that compiles intoJavaScript”Easier to read and writeA hybrid of Ruby and PythonHelpful
  • So why should Iembrace (and love) CoffeeScript?
  • String Interpolation name = Mark "Hello #{name}"
  • var name;name = Mark;"Hello " + name;
  • Heredochtml = """ <div class="comment" id="tweet-#{tweet.id_str}"> <hr> <div class=tweet> <span class="imgr"><imgsrc="#{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 <divclass=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 ConditionalsUnlessIn-line Conditionals
  • Conditionalsunless 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");}
  • FunctionsBound FunctionsDefault ArgumentsSplatted Arguments
  • Regular Functionsp = (name)-> console.log "hello: #{name}"p mark
  • var p;p = function(name) { return console.log("hello: " + name);};p(mark);
  • Regular Functionsp = (name)-> console.log "hello: #{name}"p mark
  • Regular Functionsp = (name)-> console.log "hello: #{name}" CoffeeScriptp markp = ->(name) { puts "hello: #{name}"} Ruby 1.9p.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 FunctionsfetchData: => url = "http://search.twitter.com/search.json?q=#{encodeURIComponent(@hash_tag)}&rpp=#{@max_results}&callback=?" $.get url, {}, @handleData, jsonhandleData: (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 ArgumentscreateElement: (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 Argumentssplatter = (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 Looparr = [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 Loopfor 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);}
  • ClassesEasy To DefineEasy To ExtendKeep Code Clean
  • Classesclass Employee constructor: (@name, @options = {})-> job: -> @options.jobmark = new Employee(Mark, job: Developer)mark.job() # => Developermark.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 Classesclass Manager extends Employee job: -> "$$$ #{super}"steve = new Manager(Steve, job: CEO)steve.job() # => $$$ CEOsteve.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 @markbateshttp://www.markbates.com