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

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

  • 1.
    Strangers In TheNight Gem Talk Las Palmas on Rails 11/05/2010 Alberto Perdomo http://www.fickr.com/photos/nesster/4312984219/
  • 2.
  • 3.
    Interfaz para servidoresweb, 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 ● ...
  • 8.
    DSL en Rubypara 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 arequest 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 exceptionor 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 laVidaReal®
  • 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
  • 35.
  • 36.
    panda http://github.com/newbamboo/panda Solución devideo encoding y streaming sobre Amazon S3
  • 37.
    A Sinatra legustan.. ● las microaplicaciones web ● los servicios web sin interfaz HTML ● los pequeños módulos independientes para aplicaciones web de mayor tamaño
  • 38.
  • 39.
  • 40.
  • 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