SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Strangers In The Night




                                                      Gem Talk
                                                  Las Palmas on Rails
                                                     11/05/2010


                                                   Alberto Perdomo
http://www.fickr.com/photos/nesster/4312984219/
http://www.fickr.com/photos/auxesis/4380518581/
Interfaz para servidores web,
frameworks web y middlewares
en Ruby
Servidores web

●   Thin                    ●   Mongrel
●   Ebb                     ●   EventedMongrel
●   Fuzed                   ●   SwiftipliedMongrel
●   Glassfsh v3             ●   WEBrick
●   Phusion Passenger       ●   FCGI
●   Rainbows!               ●   CGI
●   Unicorn                 ●   SCGI
●   Zbatery                 ●   LiteSpeed
Frameworks

●   Camping                        ●   Ramaze
●   Coset                          ●   Ruby on Rails
●   Halcyon                        ●   Rum
●   Mack                           ●   Sinatra
●   Maveric                        ●   Sin
●   Merb                           ●   Vintage
●   Racktools::SimpleApplication   ●   Waves
                                   ●   Wee
Middleware

●   Rack::URLMap → enrutar a distintas
    aplicaciones dentro del mismo proceso
●   Rack::CommonLogger → fcheros de log
    comunes al estilo Apache
●   Rack::ShowException → mostrar
    excepciones no captadas
●   Rack::File → servir estáticos
●   ...
DSL en Ruby para escribir aplicaciones y
servicios web de forma rápida y compacta


Funcionalidades mínimas, el desarrollador
usa las herramientas que mejor se adapten
al trabajo
Go!
  hi.rb
  require 'rubygems'
  require 'sinatra'

  get '/hi' do
    "Hello World!"
  end



$ gem install sinatra
$ ruby hi.rb
== Sinatra has taken the stage ...
>> Listening on 0.0.0.0:4567
Rutas
get '/' do
  # .. show something ..             RUTA
end
                                      =
post '/' do                      MÉTODO HTTP
  # .. create something ..            +
end                               PATRÓN URL

put '/' do
  # .. update something ..
end
                                    ORDEN
delete '/' do
  # .. annihilate something ..
end
Rutas: Parámetros

get '/hello/:name' do
  # matches "GET /hello/foo" and "GET /hello/bar"
  # params[:name] is 'foo' or 'bar'
  "Hello #{params[:name]}!"
end

get '/hello/:name' do |n|
  "Hello #{n}!"
end
Rutas: splat

get '/say/*/to/*' do
  # matches /say/hello/to/world
  params[:splat] # => ["hello", "world"]
end

get '/download/*.*' do
  # matches /download/path/to/file.xml
  params[:splat] # => ["path/to/file", "xml"]
end
Rutas: regex

get %r{/hello/([w]+)} do
  "Hello, #{params[:captures].first}!"
end

get %r{/hello/([w]+)} do |c|
  "Hello, #{c}!"
end
Rutas: condiciones

get '/foo', :agent => /Songbird (d.d)[d/]*?/ do
  "You're using Songbird v. #{params[:agent][0]}"
end

get '/foo' do
  # Matches non-songbird browsers
end
Estáticos
 ●   Por defecto en /public
 ●   /public/css/style.css →
     example.com/css/style.css
 ●   Para usar otro directorio:


set :public, File.dirname(__FILE__) + '/static'
Vistas
 ●   Por defecto en /views
 ●   Para usar otro directorio:

set :views, File.dirname(__FILE__) + '/templates'
Plantillas: HAML, ERB

## You'll need to require haml in your app
require 'haml'

get '/' do
  haml :index
end

## You'll need to require erb in your app
require 'erb'

get '/' do Renderiza /views/index.haml
  erb :index
end
Más plantillas
  ●   Erubis
  ●   Builder
  ●   Sass
  ●   Less
## You'll need to require haml or sass in your app
require 'sass'

get '/stylesheet.css' do
  content_type 'text/css', :charset => 'utf-8'
  sass :stylesheet
end
Plantillas inline



get '/' do
  haml '%div.title Hello World'
end
Variables en plantillas


get '/:id' do
  @foo = Foo.find(params[:id])
  haml '%h1= @foo.name'
end

get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1= foo.name', :locals => { :foo => foo }
end
Plantillas inline
require 'rubygems'
require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

@@ index
%div.title Hello world!!!!!
Halt
# stop a request within a filter or route
halt

# you can also specify the status when halting
halt 410

# or the body...
halt 'this will be the body'

# or both...
halt 401, 'go away!'

# with headers
halt 402, {'Content-Type' => 'text/plain'},
'revenge'
Pass

get '/guess/:who' do
  pass unless params[:who] == 'Frank'
  'You got me!'
end

get '/guess/*' do
  'You missed!'
end
Errores
# Sinatra::NotFound exception or response status code is 404
not_found do
  'This is nowhere to be found'
end

# when an exception is raised from a route block or a filter.
error do
  'Sorry there was a nasty error - ' + env['sinatra.error'].name
end

# error handler for status code
error 403 do
  'Access forbidden'
end

get '/secret' do
  403
end

# error handler for a range
error 400..510 do
  'Boom'
end
Más cosas
●   Helpers
●   Before flters
●   Error handlers
●   Code reloading
●   HTTP caching (etag, last-modifed)
Testing: Rack::Test
require 'my_sinatra_app'
require 'rack/test'

class MyAppTest < Test::Unit::TestCase
  include Rack::Test::Methods

 def app
   Sinatra::Application
 end

 def test_my_default
   get '/'
   assert_equal 'Hello World!', last_response.body
 end

 def test_with_params
   get '/meet', :name => 'Frank'
   assert_equal 'Hello Frank!', last_response.body
 end

  def test_with_rack_env
    get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
    assert_equal "You're using Songbird!", last_response.body
  end
end
Sinatra::Base
●   Para tener aplicaciones modulares y
    reusables

       require 'sinatra/base'

       class MyApp < Sinatra::Base
         set :sessions, true
         set :foo, 'bar'

         get '/' do
           'Hello world!'
         end
       end
Ejecutar la aplicación


$ ruby myapp.rb [-h] [-x] [-e ENVIRONMENT]
[-p PORT] [-o HOST] [-s HANDLER]




Busca automáticamente un servidor compatible con
       Rack con el que ejecutar la aplicación
Deployment (ejemplo)

  Apache + Passenger
  confg.ru + public
 require 'yourapp'
 set :environment, :production
 run Sinatra::Application
Ejemplos de la VidaReal®
git-wiki



         LOCs Ruby: 220
  http://github.com/sr/git-wiki

Un wiki que usa git como backend
RifGraf



             LOCs Ruby: 60
 http://github.com/adamwiggins/rifgraf

Servicio web para recolección de datos y
                gráfcas
github-services


   LOCs Ruby: 117 (sin los servicios)
http://github.com/pjhyett/github-services

 Service hooks para publicar commits
integrity




    http://integrityapp.com/

Servidor de integración continua
scanty




http://github.com/adamwiggins/scanty/

          Blog muy sencillo
panda




 http://github.com/newbamboo/panda

Solución de video encoding y streaming
           sobre Amazon S3
A Sinatra le gustan..
●   las microaplicaciones web
●   los servicios web sin interfaz HTML
●   los pequeños módulos independientes
    para aplicaciones web de mayor tamaño
Rendimiento




tinyurl.com/ruby-web-performance
Comparación en rendimiento
¿Preguntas?
Referencias
●   http://rack.rubyforge.org/

●   http://www.sinatrarb.com

●   http://www.slideshare.net/happywebcoder/alternativas-a-rails-para-sitios-y-servicios-web-ultraligeros

●   http://www.slideshare.net/adamwiggins/lightweight-webservices-with-sinatra-and-restclient-presentation

●   http://tinyurl.com/ruby-web-performance

Weitere ähnliche Inhalte

Was ist angesagt?

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails PresentationJoost Hietbrink
 
Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)srigi
 
SPARQLing Services
SPARQLing ServicesSPARQLing Services
SPARQLing ServicesLeigh Dodds
 
REST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side DevelopmentREST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side DevelopmentHyunghun Cho
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And MiddlewareBen Schwarz
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpMatthew Davis
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS IntroNgoc Dao
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsRemy Sharp
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityPeter Lubbers
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
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 LaravelBrilo Team
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 

Was ist angesagt? (20)

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Mojolicious and REST
Mojolicious and RESTMojolicious and REST
Mojolicious and REST
 
Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)Webpack & EcmaScript 6 (Webelement #32)
Webpack & EcmaScript 6 (Webelement #32)
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
SPARQLing Services
SPARQLing ServicesSPARQLing Services
SPARQLing Services
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei Presentation
 
REST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side DevelopmentREST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side Development
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And Middleware
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Express JS
Express JSExpress JS
Express JS
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
HTML5 Real-Time and Connectivity
HTML5 Real-Time and ConnectivityHTML5 Real-Time and Connectivity
HTML5 Real-Time and Connectivity
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
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
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 

Andere mochten auch

Why Semantics Matter? Adding the semantic edge to your content, right from au...
Why Semantics Matter? Adding the semantic edge to your content,right from au...Why Semantics Matter? Adding the semantic edge to your content,right from au...
Why Semantics Matter? Adding the semantic edge to your content, right from au...Ontotext
 
Live Project Training in Ahmedabad
Live Project Training in AhmedabadLive Project Training in Ahmedabad
Live Project Training in AhmedabadDevelopers Academy
 
Connecting to Your Data in the Cloud
Connecting to Your Data in the CloudConnecting to Your Data in the Cloud
Connecting to Your Data in the CloudMenSagam Technologies
 
Five Reminders about Social Media Marketing
Five Reminders about Social Media MarketingFive Reminders about Social Media Marketing
Five Reminders about Social Media MarketingDavid Berkowitz
 
High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010Barry Abrahamson
 
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...Dan Mall
 

Andere mochten auch (7)

Why Semantics Matter? Adding the semantic edge to your content, right from au...
Why Semantics Matter? Adding the semantic edge to your content,right from au...Why Semantics Matter? Adding the semantic edge to your content,right from au...
Why Semantics Matter? Adding the semantic edge to your content, right from au...
 
Live Project Training in Ahmedabad
Live Project Training in AhmedabadLive Project Training in Ahmedabad
Live Project Training in Ahmedabad
 
Connecting to Your Data in the Cloud
Connecting to Your Data in the CloudConnecting to Your Data in the Cloud
Connecting to Your Data in the Cloud
 
Five Reminders about Social Media Marketing
Five Reminders about Social Media MarketingFive Reminders about Social Media Marketing
Five Reminders about Social Media Marketing
 
High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010
 
Sure 99% intraday gold silver calls
Sure 99% intraday gold silver callsSure 99% intraday gold silver calls
Sure 99% intraday gold silver calls
 
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...
Master of None Boot Camp: Thriving and Surviving in the Aftermath of Traditio...
 

Ähnlich wie Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para construir aplicaciones y servicios web pequeños y modulares

Swing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraSwing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraMatt Gifford
 
Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01guestcaceba
 
Rack is Spectacular
Rack is SpectacularRack is Spectacular
Rack is SpectacularBryce Kerley
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!cloudbring
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Fwdays
 
plackdo, plack-like web interface on perl6
plackdo, plack-like web interface on perl6plackdo, plack-like web interface on perl6
plackdo, plack-like web interface on perl6Nobuo Danjou
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Using ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on RailsUsing ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on RailsDave Bouwman
 
Consegi 2010 - Dicas de Desenvolvimento Web com Ruby
Consegi 2010 - Dicas de Desenvolvimento Web com RubyConsegi 2010 - Dicas de Desenvolvimento Web com Ruby
Consegi 2010 - Dicas de Desenvolvimento Web com RubyFabio Akita
 
JRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudJRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudHiro Asari
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails FinalRobert Postill
 

Ähnlich wie Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para construir aplicaciones y servicios web pequeños y modulares (20)

Swing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraSwing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and Sinatra
 
Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01
 
Sinatra
SinatraSinatra
Sinatra
 
Rack is Spectacular
Rack is SpectacularRack is Spectacular
Rack is Spectacular
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)
 
Sinatra
SinatraSinatra
Sinatra
 
PSGI/Plack OSDC.TW
PSGI/Plack OSDC.TWPSGI/Plack OSDC.TW
PSGI/Plack OSDC.TW
 
plackdo, plack-like web interface on perl6
plackdo, plack-like web interface on perl6plackdo, plack-like web interface on perl6
plackdo, plack-like web interface on perl6
 
Transforming WebSockets
Transforming WebSocketsTransforming WebSockets
Transforming WebSockets
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Sprockets
SprocketsSprockets
Sprockets
 
Sinatra
SinatraSinatra
Sinatra
 
Using ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on RailsUsing ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on Rails
 
Consegi 2010 - Dicas de Desenvolvimento Web com Ruby
Consegi 2010 - Dicas de Desenvolvimento Web com RubyConsegi 2010 - Dicas de Desenvolvimento Web com Ruby
Consegi 2010 - Dicas de Desenvolvimento Web com Ruby
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
 
Ruby Kaigi 2008 LT
Ruby Kaigi 2008 LTRuby Kaigi 2008 LT
Ruby Kaigi 2008 LT
 
JRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudJRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the Cloud
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails Final
 

Mehr von Alberto Perdomo

Primeros pasos con la base de datos de grafos Neo4j
Primeros pasos con la base de datos de grafos Neo4jPrimeros pasos con la base de datos de grafos Neo4j
Primeros pasos con la base de datos de grafos Neo4jAlberto Perdomo
 
Leveraging relations at scale with Neo4j
Leveraging relations at scale with Neo4jLeveraging relations at scale with Neo4j
Leveraging relations at scale with Neo4jAlberto Perdomo
 
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...Alberto Perdomo
 
Rails for Mobile Devices @ Conferencia Rails 2011
Rails for Mobile Devices @ Conferencia Rails 2011Rails for Mobile Devices @ Conferencia Rails 2011
Rails for Mobile Devices @ Conferencia Rails 2011Alberto Perdomo
 
Boost your productivity!: Productivity tips for rails developers - Lightning ...
Boost your productivity!: Productivity tips for rails developers - Lightning ...Boost your productivity!: Productivity tips for rails developers - Lightning ...
Boost your productivity!: Productivity tips for rails developers - Lightning ...Alberto Perdomo
 
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasCurso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasAlberto Perdomo
 
Curso TDD Ruby on Rails #02: Test Driven Development
Curso TDD  Ruby on Rails #02: Test Driven DevelopmentCurso TDD  Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven DevelopmentAlberto Perdomo
 
Curso TDD Ruby on Rails #06: Mocks y stubs
Curso TDD Ruby on Rails #06: Mocks y stubsCurso TDD Ruby on Rails #06: Mocks y stubs
Curso TDD Ruby on Rails #06: Mocks y stubsAlberto Perdomo
 
Curso TDD Ruby on Rails #05: Shoulda
Curso TDD Ruby on Rails #05: ShouldaCurso TDD Ruby on Rails #05: Shoulda
Curso TDD Ruby on Rails #05: ShouldaAlberto Perdomo
 
Curso TDD Ruby on Rails #04: Factorías de objetos
Curso TDD Ruby on Rails #04: Factorías de objetosCurso TDD Ruby on Rails #04: Factorías de objetos
Curso TDD Ruby on Rails #04: Factorías de objetosAlberto Perdomo
 
Curso TDD Ruby on Rails #03: Tests unitarios
Curso TDD Ruby on Rails #03: Tests unitariosCurso TDD Ruby on Rails #03: Tests unitarios
Curso TDD Ruby on Rails #03: Tests unitariosAlberto Perdomo
 
Curso TDD Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven DevelopmentCurso TDD Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven DevelopmentAlberto Perdomo
 
Curso TDD Ruby on Rails #01: Introducción al testing
Curso TDD Ruby on Rails #01: Introducción al testingCurso TDD Ruby on Rails #01: Introducción al testing
Curso TDD Ruby on Rails #01: Introducción al testingAlberto Perdomo
 
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...Alberto Perdomo
 

Mehr von Alberto Perdomo (14)

Primeros pasos con la base de datos de grafos Neo4j
Primeros pasos con la base de datos de grafos Neo4jPrimeros pasos con la base de datos de grafos Neo4j
Primeros pasos con la base de datos de grafos Neo4j
 
Leveraging relations at scale with Neo4j
Leveraging relations at scale with Neo4jLeveraging relations at scale with Neo4j
Leveraging relations at scale with Neo4j
 
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
 
Rails for Mobile Devices @ Conferencia Rails 2011
Rails for Mobile Devices @ Conferencia Rails 2011Rails for Mobile Devices @ Conferencia Rails 2011
Rails for Mobile Devices @ Conferencia Rails 2011
 
Boost your productivity!: Productivity tips for rails developers - Lightning ...
Boost your productivity!: Productivity tips for rails developers - Lightning ...Boost your productivity!: Productivity tips for rails developers - Lightning ...
Boost your productivity!: Productivity tips for rails developers - Lightning ...
 
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticasCurso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #08: Buenas prácticas
 
Curso TDD Ruby on Rails #02: Test Driven Development
Curso TDD  Ruby on Rails #02: Test Driven DevelopmentCurso TDD  Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven Development
 
Curso TDD Ruby on Rails #06: Mocks y stubs
Curso TDD Ruby on Rails #06: Mocks y stubsCurso TDD Ruby on Rails #06: Mocks y stubs
Curso TDD Ruby on Rails #06: Mocks y stubs
 
Curso TDD Ruby on Rails #05: Shoulda
Curso TDD Ruby on Rails #05: ShouldaCurso TDD Ruby on Rails #05: Shoulda
Curso TDD Ruby on Rails #05: Shoulda
 
Curso TDD Ruby on Rails #04: Factorías de objetos
Curso TDD Ruby on Rails #04: Factorías de objetosCurso TDD Ruby on Rails #04: Factorías de objetos
Curso TDD Ruby on Rails #04: Factorías de objetos
 
Curso TDD Ruby on Rails #03: Tests unitarios
Curso TDD Ruby on Rails #03: Tests unitariosCurso TDD Ruby on Rails #03: Tests unitarios
Curso TDD Ruby on Rails #03: Tests unitarios
 
Curso TDD Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven DevelopmentCurso TDD Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #02: Test Driven Development
 
Curso TDD Ruby on Rails #01: Introducción al testing
Curso TDD Ruby on Rails #01: Introducción al testingCurso TDD Ruby on Rails #01: Introducción al testing
Curso TDD Ruby on Rails #01: Introducción al testing
 
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
 

Kürzlich hochgeladen

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 textsMaria Levchenko
 
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 Takeoffsammart93
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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 DevelopmentsTrustArc
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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.pdfhans926745
 
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 Scriptwesley chun
 
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?Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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 productivityPrincipled Technologies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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...Neo4j
 
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)wesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Kürzlich hochgeladen (20)

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
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
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?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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...
 
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)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para construir aplicaciones y servicios web pequeños y modulares

  • 1. Strangers In The Night Gem Talk Las Palmas on Rails 11/05/2010 Alberto Perdomo http://www.fickr.com/photos/nesster/4312984219/
  • 3. Interfaz para servidores web, frameworks web y middlewares en Ruby
  • 4. Servidores web ● Thin ● Mongrel ● Ebb ● EventedMongrel ● Fuzed ● SwiftipliedMongrel ● Glassfsh v3 ● WEBrick ● Phusion Passenger ● FCGI ● Rainbows! ● CGI ● Unicorn ● SCGI ● Zbatery ● LiteSpeed
  • 5. Frameworks ● Camping ● Ramaze ● Coset ● Ruby on Rails ● Halcyon ● Rum ● Mack ● Sinatra ● Maveric ● Sin ● Merb ● Vintage ● Racktools::SimpleApplication ● Waves ● Wee
  • 6. Middleware ● Rack::URLMap → enrutar a distintas aplicaciones dentro del mismo proceso ● Rack::CommonLogger → fcheros de log comunes al estilo Apache ● Rack::ShowException → mostrar excepciones no captadas ● Rack::File → servir estáticos ● ...
  • 7.
  • 8. DSL en Ruby para escribir aplicaciones y servicios web de forma rápida y compacta Funcionalidades mínimas, el desarrollador usa las herramientas que mejor se adapten al trabajo
  • 9. Go! hi.rb require 'rubygems' require 'sinatra' get '/hi' do "Hello World!" end $ gem install sinatra $ ruby hi.rb == Sinatra has taken the stage ... >> Listening on 0.0.0.0:4567
  • 10. Rutas get '/' do # .. show something .. RUTA end = post '/' do MÉTODO HTTP # .. create something .. + end PATRÓN URL put '/' do # .. update something .. end ORDEN delete '/' do # .. annihilate something .. end
  • 11. Rutas: Parámetros get '/hello/:name' do # matches "GET /hello/foo" and "GET /hello/bar" # params[:name] is 'foo' or 'bar' "Hello #{params[:name]}!" end get '/hello/:name' do |n| "Hello #{n}!" end
  • 12. Rutas: splat get '/say/*/to/*' do # matches /say/hello/to/world params[:splat] # => ["hello", "world"] end get '/download/*.*' do # matches /download/path/to/file.xml params[:splat] # => ["path/to/file", "xml"] end
  • 13. Rutas: regex get %r{/hello/([w]+)} do "Hello, #{params[:captures].first}!" end get %r{/hello/([w]+)} do |c| "Hello, #{c}!" end
  • 14. Rutas: condiciones get '/foo', :agent => /Songbird (d.d)[d/]*?/ do "You're using Songbird v. #{params[:agent][0]}" end get '/foo' do # Matches non-songbird browsers end
  • 15. Estáticos ● Por defecto en /public ● /public/css/style.css → example.com/css/style.css ● Para usar otro directorio: set :public, File.dirname(__FILE__) + '/static'
  • 16. Vistas ● Por defecto en /views ● Para usar otro directorio: set :views, File.dirname(__FILE__) + '/templates'
  • 17. Plantillas: HAML, ERB ## You'll need to require haml in your app require 'haml' get '/' do haml :index end ## You'll need to require erb in your app require 'erb' get '/' do Renderiza /views/index.haml erb :index end
  • 18. Más plantillas ● Erubis ● Builder ● Sass ● Less ## You'll need to require haml or sass in your app require 'sass' get '/stylesheet.css' do content_type 'text/css', :charset => 'utf-8' sass :stylesheet end
  • 19. Plantillas inline get '/' do haml '%div.title Hello World' end
  • 20. Variables en plantillas get '/:id' do @foo = Foo.find(params[:id]) haml '%h1= @foo.name' end get '/:id' do foo = Foo.find(params[:id]) haml '%h1= foo.name', :locals => { :foo => foo } end
  • 21. Plantillas inline require 'rubygems' require 'sinatra' get '/' do haml :index end __END__ @@ layout %html = yield @@ index %div.title Hello world!!!!!
  • 22. Halt # stop a request within a filter or route halt # you can also specify the status when halting halt 410 # or the body... halt 'this will be the body' # or both... halt 401, 'go away!' # with headers halt 402, {'Content-Type' => 'text/plain'}, 'revenge'
  • 23. Pass get '/guess/:who' do pass unless params[:who] == 'Frank' 'You got me!' end get '/guess/*' do 'You missed!' end
  • 24. Errores # Sinatra::NotFound exception or response status code is 404 not_found do 'This is nowhere to be found' end # when an exception is raised from a route block or a filter. error do 'Sorry there was a nasty error - ' + env['sinatra.error'].name end # error handler for status code error 403 do 'Access forbidden' end get '/secret' do 403 end # error handler for a range error 400..510 do 'Boom' end
  • 25. Más cosas ● Helpers ● Before flters ● Error handlers ● Code reloading ● HTTP caching (etag, last-modifed)
  • 26. Testing: Rack::Test require 'my_sinatra_app' require 'rack/test' class MyAppTest < Test::Unit::TestCase include Rack::Test::Methods def app Sinatra::Application end def test_my_default get '/' assert_equal 'Hello World!', last_response.body end def test_with_params get '/meet', :name => 'Frank' assert_equal 'Hello Frank!', last_response.body end def test_with_rack_env get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' assert_equal "You're using Songbird!", last_response.body end end
  • 27. Sinatra::Base ● Para tener aplicaciones modulares y reusables require 'sinatra/base' class MyApp < Sinatra::Base set :sessions, true set :foo, 'bar' get '/' do 'Hello world!' end end
  • 28. Ejecutar la aplicación $ ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] Busca automáticamente un servidor compatible con Rack con el que ejecutar la aplicación
  • 29. Deployment (ejemplo) Apache + Passenger confg.ru + public require 'yourapp' set :environment, :production run Sinatra::Application
  • 30. Ejemplos de la VidaReal®
  • 31. git-wiki LOCs Ruby: 220 http://github.com/sr/git-wiki Un wiki que usa git como backend
  • 32. RifGraf LOCs Ruby: 60 http://github.com/adamwiggins/rifgraf Servicio web para recolección de datos y gráfcas
  • 33. github-services LOCs Ruby: 117 (sin los servicios) http://github.com/pjhyett/github-services Service hooks para publicar commits
  • 34. integrity http://integrityapp.com/ Servidor de integración continua
  • 36. panda http://github.com/newbamboo/panda Solución de video encoding y streaming sobre Amazon S3
  • 37. A Sinatra le gustan.. ● las microaplicaciones web ● los servicios web sin interfaz HTML ● los pequeños módulos independientes para aplicaciones web de mayor tamaño
  • 41. Referencias ● http://rack.rubyforge.org/ ● http://www.sinatrarb.com ● http://www.slideshare.net/happywebcoder/alternativas-a-rails-para-sitios-y-servicios-web-ultraligeros ● http://www.slideshare.net/adamwiggins/lightweight-webservices-with-sinatra-and-restclient-presentation ● http://tinyurl.com/ruby-web-performance