SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
& Ruby


Saturday, April 17, 2010
@mbleigh

Saturday, April 17, 2010
Saturday, April 17, 2010
present.ly

Saturday, April 17, 2010
What’s Node?


Saturday, April 17, 2010
Evented I/O
                           for Javascript

Saturday, April 17, 2010
Taking JS Beyond
                     the Browser

Saturday, April 17, 2010
Runs on
                           Google’s V8

Saturday, April 17, 2010
var sys = require('sys'),
                     http = require('http');
            http.createServer(function (req, res) {
                  setTimeout(function () {
                           res.writeHead(200, {'Content-Type': 'text/plain'});
                           res.end('Hello Worldn');
                  }, 2000);
            }).listen(8000);
            sys.puts('Server running at http://127.0.0.1:8000/');




Saturday, April 17, 2010
Supported By Node

                      • HTTP, TCP
                      • File I/O
                      • Redis, Mongo, SQL (DBSlayer)

Saturday, April 17, 2010
Express: Node’s Sinatra


                      • RESTful DSL for Node webapps
                      • Cookies, sessions, caching, etc.
                      • expressjs.com

Saturday, April 17, 2010
require.paths.unshift('path/to/express/lib')
            require('express')


            get('/', function(){
                   this.redirect('/hello/world')
            })


            get('/hello/world', function(){
                   return 'Hello World'
            })


            run()



Saturday, April 17, 2010
Why Node?


Saturday, April 17, 2010
Generally Speedy


Saturday, April 17, 2010
> summary(node1$ttime)
                Min. 1st Qu.    Median        Mean   3rd Qu.     Max.
              0.0000   0.0000   1.0000      0.7437    1.0000 106.0000

            > summary(thin1$ttime)
               Min. 1st Qu. Median        Mean 3rd Qu.     Max.
              0.000   1.000   1.000      1.122   1.000   74.000

            > summary(narwhal1$ttime)
               Min. 1st Qu. Median     Mean 3rd Qu.        Max.
              15.00   22.00   23.00   23.74   24.00       88.00

            > summary(v8cgi1$ttime)
               Min. 1st Qu. Median        Mean 3rd Qu.     Max.
              12.00   13.00   13.00      14.49   18.00    39.00




                           four.livejournal.com/1019177.html



Saturday, April 17, 2010
Great at
                           Concurrency

Saturday, April 17, 2010
Asynchronous
                            Everything

Saturday, April 17, 2010
bit.ly/nodejs-fstream
            function upload_file(req, res) {
              req.setBodyEncoding('binary');

              var stream = new multipart.Stream(req);
              stream.addListener('part', function(part) {
                part.addListener('body', function(chunk) {
                  var progress = (stream.bytesReceived / stream.bytesTotal *
            100).toFixed(2);
                  var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1);

                           sys.print("Uploading "+mb+"mb ("+progress+"%)015");

                  // chunk could be appended to a file if the uploaded file needs to
            be saved
                });
              });
              stream.addListener('complete', function() {
                res.sendHeader(200, {'Content-Type': 'text/plain'});
                res.sendBody('Thanks for playing!');
                res.finish();
                sys.puts("n=> Done");
              });
            }


Saturday, April 17, 2010
Javascript is
                           great for this.

Saturday, April 17, 2010
Browser and server,
                      together at last


Saturday, April 17, 2010
Why Ruby?


Saturday, April 17, 2010
Are you at the
                            right conf?

Saturday, April 17, 2010
When to Node


Saturday, April 17, 2010
Real-Time
                           Applications

Saturday, April 17, 2010
WebSockets

                      • Persistent server connections
                      • Part of HTML5
                      • True real-time for web apps
                      • Deprecate to Flash Sockets
Saturday, April 17, 2010
Why Real-Time?

                      • Better on your server
                      • Better for your user
                      • You need more buzzwords

Saturday, April 17, 2010
var socket = new WebSocket("ws://www.websocket.org");

            socket.onopen = function(evt) { alert("Open."); };
            socket.onmessage = function(evt) { alert(evt.data); };
            socket.onclose = function(evt) { alert("Closed."); };

            socket.send("Hello Web Socket!");
            socket.close();




Saturday, April 17, 2010
Why JS for WebSockets?

                      • You already write your client
                           interaction code in Javascript
                      • Just an extension of that
                      • Same interface throughout
Saturday, April 17, 2010
Hazards of a
                           Young Tool

Saturday, April 17, 2010
node.websocket.js

                      • Framework-like approach
                      • Includes fun examples
                      • Node version headaches
                      • github.com/guille/node.websocket.js/

Saturday, April 17, 2010
Socket.IO

                      • Multi-transport socket for Node
                      • Comes with client JS library
                      • For production usage
                      • github.com/rosepad/socket.io-node

Saturday, April 17, 2010
node.ws.js
                      • Minimal Node WebSocket server
                      • Talk to your browser clients
                      • Javascript all the way down
                      • Mostly for experimentation
                      • github.com/ncr/node.ws.js
Saturday, April 17, 2010
How can we
                           actually use it?

Saturday, April 17, 2010
Redis is the Bridge

                      • Super-fast, super-awesome
                      • PUBSUB = WIN!
                      • Swiss-army knife for your app.

Saturday, April 17, 2010
Example

                      • Twitter-esque status streams
                      • Want to update web interface in
                           real time
                      • Rails, Node, Redis, and Chrome
Saturday, April 17, 2010
The Ruby Code


Saturday, April 17, 2010
class User < ActiveRecord::Base
              # Include default devise modules. Others available are:
              # :token_authenticatable, :lockable and :timeoutable
              devise :database_authenticatable, :registerable, :rememberable, :validatable

                # Setup accessible (or protected) attributes for your model
                attr_accessible :email, :password, :password_confirmation

                def follow(other_user)
                  Red.sadd "user:#{other_user.id}:followers", self.id
                  Red.sadd "user:#{self.id}:follows", other_user.id
                end

                def follower_ids
                  Red.smembers "user:#{self.id}:followers"
                end

                def follow_ids
                  Red.smembers "user:#{self.id}:follows"
                end

              def update(text)
                (follower_ids + [self.id]).each do |uid|
                  Red.lpush "user:#{uid}:timeline", text
                  Red.lpush "user:#{uid}:updates", text
                  Red.publish "user:#{uid}:timeline", text
                end
              end
            end




Saturday, April 17, 2010
def update(text)
                     (follower_ids + [self.id]).each do |uid|
                       Red.lpush "user:#{uid}:timeline", text
                       Red.lpush "user:#{uid}:updates", text
                       Red.publish "user:#{uid}:timeline", text
                     end
                   end




Saturday, April 17, 2010
The Node Code


Saturday, April 17, 2010
var sys = require("sys"),
                ws = require("./ws"),
                redis = require("./redis-client");

            var pubsub = redis.createClient();

            pubsub.stream.addListener('connect', function() {
              pubsub.subscribeTo("user:*:timeline", function(channel, data) {
                var uid = channel.toString().split(':')[1];

                if (clients[uid]) {
                  sys.debug("Writing " + data + " to " + uid)
                  clients[uid].write(data);
                } else {
                  sys.debug("User " + clients[uid] + " is not connected.");
                }
              });
            });

            ws.createServer(function (websocket) {
              var user_id = null;
              var websocket = websocket;

              websocket.addListener("connect", function (resource) {
                user_id = resource.match(/timeline/([0-9]+)$/i)[1]
                clients[user_id] = websocket;
              }).addListener("close", function() {
                sys.debug("User " + user_id + " disconnected.")
              });
            }).listen(8080);




Saturday, April 17, 2010
ws.createServer(function (websocket) {
                  var user_id = null;
                  var websocket = websocket;


                  websocket.addListener("connect", function (resource) {
                       user_id = resource.match(/timeline/([0-9]+)$/i)[1]
                       clients[user_id] = websocket;
                  }).addListener("close", function() {
                       sys.debug("User " + user_id + " disconnected.")
                  });
            }).listen(8080);




Saturday, April 17, 2010
pubsub.stream.addListener('connect', function() {
                 pubsub.subscribeTo("user:*:timeline", function(channel, data) {
                      var uid = channel.toString().split(':')[1];


                      if (clients[uid]) {
                           sys.debug("Writing " + data + " to " + uid)
                           clients[uid].write(data);
                      } else {
                           sys.debug("User " + clients[uid] + " is not connected.");
                      }
                 });
            });




Saturday, April 17, 2010
The Browser Code


Saturday, April 17, 2010
if ("WebSocket" in window) {
              var ws = new WebSocket("ws://127.0.0.1:8080/timeline/" +
            current_user);

                 ws.onmessage = function(evt) {
                   $('ul.timeline').prepend("<li>" + evt.data + "</li>");
                 }
            }




Saturday, April 17, 2010
How else can we
                       use Node?

Saturday, April 17, 2010
Asynchronous
                           Applications

Saturday, April 17, 2010
Push APIs

                      • Want to notify API subscribers in
                           real-time
                      • Utilize Webhooks
                      • Example: GitHub’s Service Hooks
Saturday, April 17, 2010
Saturday, April 17, 2010
File Transcoding


Saturday, April 17, 2010
Saturday, April 17, 2010
Online Gaming


Saturday, April 17, 2010
Ephemeral
                           Peer-to-Peer

Saturday, April 17, 2010
Wrapping up...


Saturday, April 17, 2010
Tip of the Iceberg

                      • Node’s libraries and use cases
                           are expanding rapidly
                      • Async means thinking differently
                      • Still at the early stages
Saturday, April 17, 2010
howtonode.org


Saturday, April 17, 2010
Node for Ruby?


Saturday, April 17, 2010
EventMachine


Saturday, April 17, 2010
Cramp


Saturday, April 17, 2010
Use what feels right.



Saturday, April 17, 2010
I don’t know
                           the half of it.

Saturday, April 17, 2010
Questions?


Saturday, April 17, 2010

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devmcantelon
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don'tF5 Buddy
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaNurul Ferdous
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs Irfan Maulana
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBHengki Sihombing
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSRoss Kukulinski
 

Was ist angesagt? (20)

Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal dev
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
NodeJS
NodeJSNodeJS
NodeJS
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
NodeJS
NodeJSNodeJS
NodeJS
 

Andere mochten auch

Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it doesGabriele Lana
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 
Node.js - un poco de informacion.
Node.js - un poco de informacion.Node.js - un poco de informacion.
Node.js - un poco de informacion.Luis Toscano
 
Converting a Rails application to Node.js
Converting a Rails application to Node.jsConverting a Rails application to Node.js
Converting a Rails application to Node.jsMatt Sergeant
 
De-Risking Your Startup -- SaaStr 2017 Talk
De-Risking Your Startup -- SaaStr 2017 TalkDe-Risking Your Startup -- SaaStr 2017 Talk
De-Risking Your Startup -- SaaStr 2017 TalkLeo Polovets
 
Eric Ries - The Lean Startup - Google Tech Talk
Eric Ries - The Lean Startup - Google Tech TalkEric Ries - The Lean Startup - Google Tech Talk
Eric Ries - The Lean Startup - Google Tech TalkEric Ries
 
Minimum Viable Product
Minimum Viable ProductMinimum Viable Product
Minimum Viable ProductEric Ries
 
Node.js and The Internet of Things
Node.js and The Internet of ThingsNode.js and The Internet of Things
Node.js and The Internet of ThingsLosant
 

Andere mochten auch (10)

Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it does
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Node.js - un poco de informacion.
Node.js - un poco de informacion.Node.js - un poco de informacion.
Node.js - un poco de informacion.
 
Converting a Rails application to Node.js
Converting a Rails application to Node.jsConverting a Rails application to Node.js
Converting a Rails application to Node.js
 
De-Risking Your Startup -- SaaStr 2017 Talk
De-Risking Your Startup -- SaaStr 2017 TalkDe-Risking Your Startup -- SaaStr 2017 Talk
De-Risking Your Startup -- SaaStr 2017 Talk
 
Eric Ries - The Lean Startup - Google Tech Talk
Eric Ries - The Lean Startup - Google Tech TalkEric Ries - The Lean Startup - Google Tech Talk
Eric Ries - The Lean Startup - Google Tech Talk
 
Minimum Viable Product
Minimum Viable ProductMinimum Viable Product
Minimum Viable Product
 
Node.js and The Internet of Things
Node.js and The Internet of ThingsNode.js and The Internet of Things
Node.js and The Internet of Things
 

Ähnlich wie Node.js and Ruby

Building Distributed JavaScript Widgets with jQuery
Building Distributed JavaScript Widgets with jQueryBuilding Distributed JavaScript Widgets with jQuery
Building Distributed JavaScript Widgets with jQuerybenvinegar
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New HotnessDaniel Shaw
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!Matt Butcher
 
MongoDB, Node.js And You: PART II
MongoDB, Node.js And You: PART IIMongoDB, Node.js And You: PART II
MongoDB, Node.js And You: PART IIMitch Pirtle
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Document-Oriented Databases: Couchdb Primer
Document-Oriented Databases: Couchdb PrimerDocument-Oriented Databases: Couchdb Primer
Document-Oriented Databases: Couchdb Primerjsiarto
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Edted 2010 Ruby on Rails
Edted 2010 Ruby on RailsEdted 2010 Ruby on Rails
Edted 2010 Ruby on RailsFabio Akita
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Adrian Olaru
 
Debugging and Profiling Symfony Apps
Debugging and Profiling Symfony AppsDebugging and Profiling Symfony Apps
Debugging and Profiling Symfony AppsAlvaro Videla
 
A (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIA (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIEdward B. Rockower
 

Ähnlich wie Node.js and Ruby (20)

Building Distributed JavaScript Widgets with jQuery
Building Distributed JavaScript Widgets with jQueryBuilding Distributed JavaScript Widgets with jQuery
Building Distributed JavaScript Widgets with jQuery
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New Hotness
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim Summit
 
Symfony in the Cloud
Symfony in the CloudSymfony in the Cloud
Symfony in the Cloud
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!QueryPath: It's like PHP jQuery in Drupal!
QueryPath: It's like PHP jQuery in Drupal!
 
Is these a bug
Is these a bugIs these a bug
Is these a bug
 
MongoDB, Node.js And You: PART II
MongoDB, Node.js And You: PART IIMongoDB, Node.js And You: PART II
MongoDB, Node.js And You: PART II
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Document-Oriented Databases: Couchdb Primer
Document-Oriented Databases: Couchdb PrimerDocument-Oriented Databases: Couchdb Primer
Document-Oriented Databases: Couchdb Primer
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Edted 2010 Ruby on Rails
Edted 2010 Ruby on RailsEdted 2010 Ruby on Rails
Edted 2010 Ruby on Rails
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Základy GWT
Základy GWTZáklady GWT
Základy GWT
 
Debugging and Profiling Symfony Apps
Debugging and Profiling Symfony AppsDebugging and Profiling Symfony Apps
Debugging and Profiling Symfony Apps
 
A (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio APIA (Mis-) Guided Tour of the Web Audio API
A (Mis-) Guided Tour of the Web Audio API
 

Mehr von Michael Bleigh

OmniAuth: From the Ground Up (RailsConf 2011)
OmniAuth: From the Ground Up (RailsConf 2011)OmniAuth: From the Ground Up (RailsConf 2011)
OmniAuth: From the Ground Up (RailsConf 2011)Michael Bleigh
 
OmniAuth: From the Ground Up
OmniAuth: From the Ground UpOmniAuth: From the Ground Up
OmniAuth: From the Ground UpMichael Bleigh
 
The Grapes of Rapid (RubyConf 2010)
The Grapes of Rapid (RubyConf 2010)The Grapes of Rapid (RubyConf 2010)
The Grapes of Rapid (RubyConf 2010)Michael Bleigh
 
Deciphering the Interoperable Web
Deciphering the Interoperable WebDeciphering the Interoperable Web
Deciphering the Interoperable WebMichael Bleigh
 
The Present Future of OAuth
The Present Future of OAuthThe Present Future of OAuth
The Present Future of OAuthMichael Bleigh
 
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)Michael Bleigh
 
Hacking the Mid-End (Great Lakes Ruby Bash Edition)
Hacking the Mid-End (Great Lakes Ruby Bash Edition)Hacking the Mid-End (Great Lakes Ruby Bash Edition)
Hacking the Mid-End (Great Lakes Ruby Bash Edition)Michael Bleigh
 

Mehr von Michael Bleigh (10)

OmniAuth: From the Ground Up (RailsConf 2011)
OmniAuth: From the Ground Up (RailsConf 2011)OmniAuth: From the Ground Up (RailsConf 2011)
OmniAuth: From the Ground Up (RailsConf 2011)
 
OmniAuth: From the Ground Up
OmniAuth: From the Ground UpOmniAuth: From the Ground Up
OmniAuth: From the Ground Up
 
The Grapes of Rapid (RubyConf 2010)
The Grapes of Rapid (RubyConf 2010)The Grapes of Rapid (RubyConf 2010)
The Grapes of Rapid (RubyConf 2010)
 
Upgrading to Rails 3
Upgrading to Rails 3Upgrading to Rails 3
Upgrading to Rails 3
 
Deciphering the Interoperable Web
Deciphering the Interoperable WebDeciphering the Interoperable Web
Deciphering the Interoperable Web
 
The Present Future of OAuth
The Present Future of OAuthThe Present Future of OAuth
The Present Future of OAuth
 
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)Persistence  Smoothie: Blending SQL and NoSQL (RubyNation Edition)
Persistence Smoothie: Blending SQL and NoSQL (RubyNation Edition)
 
Persistence Smoothie
Persistence SmoothiePersistence Smoothie
Persistence Smoothie
 
Twitter on Rails
Twitter on RailsTwitter on Rails
Twitter on Rails
 
Hacking the Mid-End (Great Lakes Ruby Bash Edition)
Hacking the Mid-End (Great Lakes Ruby Bash Edition)Hacking the Mid-End (Great Lakes Ruby Bash Edition)
Hacking the Mid-End (Great Lakes Ruby Bash Edition)
 

Node.js and Ruby

  • 6. Evented I/O for Javascript Saturday, April 17, 2010
  • 7. Taking JS Beyond the Browser Saturday, April 17, 2010
  • 8. Runs on Google’s V8 Saturday, April 17, 2010
  • 9. var sys = require('sys'), http = require('http'); http.createServer(function (req, res) { setTimeout(function () { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }, 2000); }).listen(8000); sys.puts('Server running at http://127.0.0.1:8000/'); Saturday, April 17, 2010
  • 10. Supported By Node • HTTP, TCP • File I/O • Redis, Mongo, SQL (DBSlayer) Saturday, April 17, 2010
  • 11. Express: Node’s Sinatra • RESTful DSL for Node webapps • Cookies, sessions, caching, etc. • expressjs.com Saturday, April 17, 2010
  • 12. require.paths.unshift('path/to/express/lib') require('express') get('/', function(){ this.redirect('/hello/world') }) get('/hello/world', function(){ return 'Hello World' }) run() Saturday, April 17, 2010
  • 15. > summary(node1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0000 0.0000 1.0000 0.7437 1.0000 106.0000 > summary(thin1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000 1.000 1.000 1.122 1.000 74.000 > summary(narwhal1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 15.00 22.00 23.00 23.74 24.00 88.00 > summary(v8cgi1$ttime) Min. 1st Qu. Median Mean 3rd Qu. Max. 12.00 13.00 13.00 14.49 18.00 39.00 four.livejournal.com/1019177.html Saturday, April 17, 2010
  • 16. Great at Concurrency Saturday, April 17, 2010
  • 17. Asynchronous Everything Saturday, April 17, 2010
  • 18. bit.ly/nodejs-fstream function upload_file(req, res) { req.setBodyEncoding('binary'); var stream = new multipart.Stream(req); stream.addListener('part', function(part) { part.addListener('body', function(chunk) { var progress = (stream.bytesReceived / stream.bytesTotal * 100).toFixed(2); var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1); sys.print("Uploading "+mb+"mb ("+progress+"%)015"); // chunk could be appended to a file if the uploaded file needs to be saved }); }); stream.addListener('complete', function() { res.sendHeader(200, {'Content-Type': 'text/plain'}); res.sendBody('Thanks for playing!'); res.finish(); sys.puts("n=> Done"); }); } Saturday, April 17, 2010
  • 19. Javascript is great for this. Saturday, April 17, 2010
  • 20. Browser and server, together at last Saturday, April 17, 2010
  • 22. Are you at the right conf? Saturday, April 17, 2010
  • 23. When to Node Saturday, April 17, 2010
  • 24. Real-Time Applications Saturday, April 17, 2010
  • 25. WebSockets • Persistent server connections • Part of HTML5 • True real-time for web apps • Deprecate to Flash Sockets Saturday, April 17, 2010
  • 26. Why Real-Time? • Better on your server • Better for your user • You need more buzzwords Saturday, April 17, 2010
  • 27. var socket = new WebSocket("ws://www.websocket.org"); socket.onopen = function(evt) { alert("Open."); }; socket.onmessage = function(evt) { alert(evt.data); }; socket.onclose = function(evt) { alert("Closed."); }; socket.send("Hello Web Socket!"); socket.close(); Saturday, April 17, 2010
  • 28. Why JS for WebSockets? • You already write your client interaction code in Javascript • Just an extension of that • Same interface throughout Saturday, April 17, 2010
  • 29. Hazards of a Young Tool Saturday, April 17, 2010
  • 30. node.websocket.js • Framework-like approach • Includes fun examples • Node version headaches • github.com/guille/node.websocket.js/ Saturday, April 17, 2010
  • 31. Socket.IO • Multi-transport socket for Node • Comes with client JS library • For production usage • github.com/rosepad/socket.io-node Saturday, April 17, 2010
  • 32. node.ws.js • Minimal Node WebSocket server • Talk to your browser clients • Javascript all the way down • Mostly for experimentation • github.com/ncr/node.ws.js Saturday, April 17, 2010
  • 33. How can we actually use it? Saturday, April 17, 2010
  • 34. Redis is the Bridge • Super-fast, super-awesome • PUBSUB = WIN! • Swiss-army knife for your app. Saturday, April 17, 2010
  • 35. Example • Twitter-esque status streams • Want to update web interface in real time • Rails, Node, Redis, and Chrome Saturday, April 17, 2010
  • 36. The Ruby Code Saturday, April 17, 2010
  • 37. class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :lockable and :timeoutable devise :database_authenticatable, :registerable, :rememberable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation def follow(other_user) Red.sadd "user:#{other_user.id}:followers", self.id Red.sadd "user:#{self.id}:follows", other_user.id end def follower_ids Red.smembers "user:#{self.id}:followers" end def follow_ids Red.smembers "user:#{self.id}:follows" end def update(text) (follower_ids + [self.id]).each do |uid| Red.lpush "user:#{uid}:timeline", text Red.lpush "user:#{uid}:updates", text Red.publish "user:#{uid}:timeline", text end end end Saturday, April 17, 2010
  • 38. def update(text) (follower_ids + [self.id]).each do |uid| Red.lpush "user:#{uid}:timeline", text Red.lpush "user:#{uid}:updates", text Red.publish "user:#{uid}:timeline", text end end Saturday, April 17, 2010
  • 39. The Node Code Saturday, April 17, 2010
  • 40. var sys = require("sys"), ws = require("./ws"), redis = require("./redis-client"); var pubsub = redis.createClient(); pubsub.stream.addListener('connect', function() { pubsub.subscribeTo("user:*:timeline", function(channel, data) { var uid = channel.toString().split(':')[1]; if (clients[uid]) { sys.debug("Writing " + data + " to " + uid) clients[uid].write(data); } else { sys.debug("User " + clients[uid] + " is not connected."); } }); }); ws.createServer(function (websocket) { var user_id = null; var websocket = websocket; websocket.addListener("connect", function (resource) { user_id = resource.match(/timeline/([0-9]+)$/i)[1] clients[user_id] = websocket; }).addListener("close", function() { sys.debug("User " + user_id + " disconnected.") }); }).listen(8080); Saturday, April 17, 2010
  • 41. ws.createServer(function (websocket) { var user_id = null; var websocket = websocket; websocket.addListener("connect", function (resource) { user_id = resource.match(/timeline/([0-9]+)$/i)[1] clients[user_id] = websocket; }).addListener("close", function() { sys.debug("User " + user_id + " disconnected.") }); }).listen(8080); Saturday, April 17, 2010
  • 42. pubsub.stream.addListener('connect', function() { pubsub.subscribeTo("user:*:timeline", function(channel, data) { var uid = channel.toString().split(':')[1]; if (clients[uid]) { sys.debug("Writing " + data + " to " + uid) clients[uid].write(data); } else { sys.debug("User " + clients[uid] + " is not connected."); } }); }); Saturday, April 17, 2010
  • 43. The Browser Code Saturday, April 17, 2010
  • 44. if ("WebSocket" in window) { var ws = new WebSocket("ws://127.0.0.1:8080/timeline/" + current_user); ws.onmessage = function(evt) { $('ul.timeline').prepend("<li>" + evt.data + "</li>"); } } Saturday, April 17, 2010
  • 45. How else can we use Node? Saturday, April 17, 2010
  • 46. Asynchronous Applications Saturday, April 17, 2010
  • 47. Push APIs • Want to notify API subscribers in real-time • Utilize Webhooks • Example: GitHub’s Service Hooks Saturday, April 17, 2010
  • 52. Ephemeral Peer-to-Peer Saturday, April 17, 2010
  • 54. Tip of the Iceberg • Node’s libraries and use cases are expanding rapidly • Async means thinking differently • Still at the early stages Saturday, April 17, 2010
  • 56. Node for Ruby? Saturday, April 17, 2010
  • 59. Use what feels right. Saturday, April 17, 2010
  • 60. I don’t know the half of it. Saturday, April 17, 2010