SlideShare a Scribd company logo
1 of 38
Encheção de linguiça :D




                          @dev_ton
Olá!




       @dev_ton
eu

Antônio Roberto ( ton )
e você




                          @dev_ton
2009


       @dev_ton
@dev_ton
Leroy




eu




             @dev_ton
@dev_ton
@dev_ton
apoio



        @dev_ton
Introdução ao
CRAMP e WebSockets

       apoio



                     @dev_ton
CRAMP



        @dev_ton
CRAMP

- O que é?
- Quando usar?




                         @dev_ton
CRAMP
Controller & Model




                     @dev_ton
CRAMP
Cramp::Controller

Os 4 estágios após uma requisição:
Initialization
Response Initialization
Starting
Finishing




                                     @dev_ton
CRAMP
Cramp::Controller
Helpers:
on_start
before_start
on_finish
periodic_timer
keep_connection_alive
respond_with
request_limit_exceeded




                                 @dev_ton
CRAMP
Cramp::Controller
on_start

 class Hello < Cramp::Controller::Action
   on_start :say_hello

   def say_hello
     render "Hello World! :)"
     finish
   end
 end



                                           @dev_ton
CRAMP
Cramp::Controller
before_start

 before_start :valid_param

 def valid_user
   if param[:id] =~ /[^a-zA-Z](.*)/
     yield
   else
     halt 500, {'Content-Type' => 'text/plain'}, "Invalid ID"
   end
 end


                                                                @dev_ton
CRAMP
Cramp::Controller
on_finish
 class PollUserAction < Cramp::Controller::Action
   on_start :start_polling
   on_finish :stop_polling

   def start_polling
     # Call find_user every 10 seconds
     @timer = EventMachine::PeriodicTimer.new(2) { find_user }
   end

   def find_user
     User.first {|u| render "#{u.inspect}n" }
   end

   def stop_polling
     puts "Cancelling the timer.."
     @timer.cancel
   end
 end



                                                                 @dev_ton
CRAMP
Cramp::Controller
periodic_timer

 class PollUserAction < Cramp::Controller::Action
   periodic_timer :poll_user, :every => 2

   def poll_user
     User.first {|u| render "#{u.inspect}n" }
   end
 end



                                                    @dev_ton
CRAMP
Cramp::Controller
keep_connection_alive


 class PollUserAction < Cramp::Controller::Action
   periodic_timer :poll_user, :every => 2
   keep_connection_alive, :every => 30
 end




                                                    @dev_ton
CRAMP
Cramp::Controller
respond_with


 def respond_with
   content_type = params[:format] == 'xml' ? 'application/xml' : 'application/json'
   [200, {'Content-Type' => content_type}]
 end




                                                                                 @dev_ton
CRAMP
Cramp::Controller
request_limit_exceeded
 class PollUserAction < Cramp::Controller::Action
   periodic_timer :poll_user, :every => 2
   periodic_timer :check_limit_exceed, :every => 10

   def poll_user
     ..
   end

   def check_limit_exceed
     finish if request_limit_exceeded
   end
 end


                                                      @dev_ton
CRAMP
Cramp::Model




                       @dev_ton
CRAMP
Cramp::Model




                :(
                       @dev_ton
CRAMP
Cramp::Model

Cramp::Model.init(:username => 'root', :database =>
'cramp_development')

class User < Cramp::Model::Base
  attribute :id, :type => Integer, :primary_key => true
  attribute :name

  validates_presence_of :name
end




                                                          @dev_ton
CRAMP
Cramp::Model

EM.run do
  User.select(:id, :name).limit(10).offset(20).first {|u| .. }
  User.where(User[:name].eq('Lush')).limit(2).all {|users| ... }
  User.each {|user| .. }

  def lush_users_found(users)
    ...
  end

  User.where(User[:name].eq('Lush'), User[:id].gt(5)).all
method(:lush_users_found)
end




                                                                   @dev_ton
CRAMP
Cramp::Model

EM.run do
  def user_saved(status)
    if status.success?
      ...
    else
      user = status.record
      puts "Oops. Found errors : #{status.record.errors.inspect}"
    end
  end

  user = User.new
  user.save method(:user_saved)
end




                                                                    @dev_ton
WebSocket



            @dev_ton
WebSocket
  A mágica!




              @dev_ton
WebSocket
                              4 passos

var location = 'http://localhost:8080/backend';
var socket = new WebSocket(location);

socket.onopen = function(data) { ... };

socket.onmessage = function(data) {... };

socket.onclose = function(data) { ... };

socket.send(data);


https://gist.github.com/98c8448ba054b7992aff#file_example.js



                                                              @dev_ton
WebSocket
   &
 CRAMP


            @dev_ton
WebSocket & CRAMP
Cramp::Controller::Websocket


Cramp::Controller::Websocket.backend = :thin



on_data




                                               @dev_ton
WebSocket & CRAMP
on_data

 Cramp::Controller::Websocket.backend = :thin

 class WelcomeController < Cramp::Controller::Websocket
   on_data :received_data

   def received_data(data)
     render "Got your #{data}"
   end
 end


https://gist.github.com/d04affd72e2ea57039eb




                                                          @dev_ton
Ajax & WebSockets




                    @dev_ton
DEMO :D



          @dev_ton
Obrigado! :)

email: forevertonny@gmail.com
twitter: @dev_ton
links
Indrodução ao CRAMP & WebSockets ( patrik )
http://m.onkey.org/2010/1/7/introducing-cramp
http://m.onkey.org/2010/1/15/websockets-made-easy-with-cramp

WebSockets API
http://dev.w3.org/html5/websockets/

Video ( pubsubhubbub )
http://www.youtube.com/watch?v=B5kHx0rGkec

App Apresentação
http://github.com/devton/socketchat




                                                               @dev_ton
Obrigado!




            @dev_ton

More Related Content

What's hot

Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in Eclipse
Tom Arend
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event Dispatcher
Sarah El-Atm
 
Design patterns as power of programing
Design patterns as power of programingDesign patterns as power of programing
Design patterns as power of programing
Lukas Lesniewski
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and http
Kaniska Mandal
 

What's hot (20)

Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in Eclipse
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdown
 
Installing symfony within netbeans and WAMP
Installing symfony within netbeans and WAMPInstalling symfony within netbeans and WAMP
Installing symfony within netbeans and WAMP
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event Dispatcher
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
GTLAB Overview
GTLAB OverviewGTLAB Overview
GTLAB Overview
 
Php Debugger
Php DebuggerPhp Debugger
Php Debugger
 
No Hugging, No Learning
No Hugging, No LearningNo Hugging, No Learning
No Hugging, No Learning
 
Speedy TDD with Rails
Speedy TDD with RailsSpeedy TDD with Rails
Speedy TDD with Rails
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Design patterns as power of programing
Design patterns as power of programingDesign patterns as power of programing
Design patterns as power of programing
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
WP Weekend #2 - Corcel, aneb WordPress přes Laravel
WP Weekend #2 - Corcel, aneb WordPress přes LaravelWP Weekend #2 - Corcel, aneb WordPress přes Laravel
WP Weekend #2 - Corcel, aneb WordPress přes Laravel
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and http
 
Java do-while Loop
Java do-while LoopJava do-while Loop
Java do-while Loop
 

Viewers also liked

Scald injury powerpointpresentation
Scald injury powerpointpresentationScald injury powerpointpresentation
Scald injury powerpointpresentation
Ashland KY Fire Dept
 
Athletes nutrition and optimum performance
Athletes nutrition and optimum performanceAthletes nutrition and optimum performance
Athletes nutrition and optimum performance
c3162739
 
Land disposal of waste and Environmental pollution
Land disposal of waste and Environmental pollutionLand disposal of waste and Environmental pollution
Land disposal of waste and Environmental pollution
Chanuk Liyanage
 

Viewers also liked (16)

Care and Nutrition for a Sick Child
Care and Nutrition for a Sick ChildCare and Nutrition for a Sick Child
Care and Nutrition for a Sick Child
 
Scald injury powerpointpresentation
Scald injury powerpointpresentationScald injury powerpointpresentation
Scald injury powerpointpresentation
 
Nutrition in sick children
Nutrition in sick childrenNutrition in sick children
Nutrition in sick children
 
Athletes nutrition and optimum performance
Athletes nutrition and optimum performanceAthletes nutrition and optimum performance
Athletes nutrition and optimum performance
 
Food, nutrition and exercise
Food, nutrition and exerciseFood, nutrition and exercise
Food, nutrition and exercise
 
Child nutrition
Child nutritionChild nutrition
Child nutrition
 
Land disposal of waste and Environmental pollution
Land disposal of waste and Environmental pollutionLand disposal of waste and Environmental pollution
Land disposal of waste and Environmental pollution
 
Sports nutrition
Sports nutritionSports nutrition
Sports nutrition
 
Sports Injuries
Sports InjuriesSports Injuries
Sports Injuries
 
Strain sprain fracture
Strain sprain fractureStrain sprain fracture
Strain sprain fracture
 
fracture and dislocation ppt . Almas khan. khorfakkhan hospital dubai
fracture and dislocation ppt . Almas khan. khorfakkhan hospital dubaifracture and dislocation ppt . Almas khan. khorfakkhan hospital dubai
fracture and dislocation ppt . Almas khan. khorfakkhan hospital dubai
 
Poisoning
PoisoningPoisoning
Poisoning
 
Methods of waste disposal reduce, reuse , recovery, recycle
Methods of waste disposal reduce, reuse , recovery, recycleMethods of waste disposal reduce, reuse , recovery, recycle
Methods of waste disposal reduce, reuse , recovery, recycle
 
Burns
BurnsBurns
Burns
 
Waste disposal
Waste disposalWaste disposal
Waste disposal
 
Wound Healing & Wound Care
Wound Healing & Wound CareWound Healing & Wound Care
Wound Healing & Wound Care
 

Similar to Cramp websockets

Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
Juan Maiz
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
aeden_brines
 

Similar to Cramp websockets (20)

Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Aprendendo solid com exemplos
Aprendendo solid com exemplosAprendendo solid com exemplos
Aprendendo solid com exemplos
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
TDC 2015 - DSLs em Ruby
TDC 2015 - DSLs em RubyTDC 2015 - DSLs em Ruby
TDC 2015 - DSLs em Ruby
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Capistrano Overview
Capistrano OverviewCapistrano Overview
Capistrano Overview
 
My name is Trinidad
My name is TrinidadMy name is Trinidad
My name is Trinidad
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Puppet Camp DC 2015: Distributed OpenSCAP Compliance Validation with MCollective
Puppet Camp DC 2015: Distributed OpenSCAP Compliance Validation with MCollectivePuppet Camp DC 2015: Distributed OpenSCAP Compliance Validation with MCollective
Puppet Camp DC 2015: Distributed OpenSCAP Compliance Validation with MCollective
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Palestra "Do PHP ao Rails" - FOCAI
Palestra "Do PHP ao Rails" - FOCAIPalestra "Do PHP ao Rails" - FOCAI
Palestra "Do PHP ao Rails" - FOCAI
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Cramp websockets

Editor's Notes