Successfully reported this slideshow.
Strangers In The Night




                                                      Gem Talk
                                ...
http://www.fickr.com/photos/auxesis/4380518581/
Interfaz para servidores web,
frameworks web y middlewares
en Ruby
Servidores web

●   Thin                    ●   Mongrel
●   Ebb                     ●   EventedMongrel
●   Fuzed          ...
Frameworks

●   Camping                        ●   Ramaze
●   Coset                          ●   Ruby on Rails
●   Halcyon...
Middleware

●   Rack::URLMap → enrutar a distintas
    aplicaciones dentro del mismo proceso
●   Rack::CommonLogger → fche...
DSL en Ruby para escribir aplicaciones y
servicios web de forma rápida y compacta


Funcionalidades mínimas, el desarrolla...
Go!
  hi.rb
  require 'rubygems'
  require 'sinatra'

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



$ gem install sinatra
$ r...
Rutas
get '/' do
  # .. show something ..             RUTA
end
                                      =
post '/' do        ...
Rutas: Parámetros

get '/hello/:name' do
  # matches "GET /hello/foo" and "GET /hello/bar"
  # params[:name] is 'foo' or '...
Rutas: splat

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

get '/dow...
Rutas: regex

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

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

get '/foo', :agent => /Songbird (d.d)[d/]*?/ do
  "You're using Songbird v. #{params[:agent][0]}"
end
...
Estáticos
 ●   Por defecto en /public
 ●   /public/css/style.css →
     example.com/css/style.css
 ●   Para usar otro dire...
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 ...
Más plantillas
  ●   Erubis
  ●   Builder
  ●   Sass
  ●   Less
## You'll need to require haml or sass in your app
require...
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 = ...
Plantillas inline
require 'rubygems'
require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

...
Halt
# stop a request within a filter or route
halt

# you can also specify the status when halting
halt 410

# or the bod...
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

# w...
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::T...
Sinatra::Base
●   Para tener aplicaciones modulares y
    reusables

       require 'sinatra/base'

       class MyApp < S...
Ejecutar la aplicación


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




Busca automáticam...
Deployment (ejemplo)

  Apache + Passenger
  confg.ru + public
 require 'yourapp'
 set :environment, :production
 run Sina...
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
   ...
github-services


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

 Service hooks para pub...
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 indep...
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/alte...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para construir aplicaciones y servicios web pequeños ...
Upcoming SlideShare
Loading in …5
×

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

8,749 views

Published on

Gemtalk en Las Palmas on Rails 11/05/2010

Published in: Technology

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

  1. 1. Strangers In The Night Gem Talk Las Palmas on Rails 11/05/2010 Alberto Perdomo http://www.fickr.com/photos/nesster/4312984219/
  2. 2. http://www.fickr.com/photos/auxesis/4380518581/
  3. 3. Interfaz para servidores web, frameworks web y middlewares en Ruby
  4. 4. Servidores web ● Thin ● Mongrel ● Ebb ● EventedMongrel ● Fuzed ● SwiftipliedMongrel ● Glassfsh v3 ● WEBrick ● Phusion Passenger ● FCGI ● Rainbows! ● CGI ● Unicorn ● SCGI ● Zbatery ● LiteSpeed
  5. 5. Frameworks ● Camping ● Ramaze ● Coset ● Ruby on Rails ● Halcyon ● Rum ● Mack ● Sinatra ● Maveric ● Sin ● Merb ● Vintage ● Racktools::SimpleApplication ● Waves ● Wee
  6. 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. 7. 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
  8. 8. 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
  9. 9. 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
  10. 10. 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
  11. 11. 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
  12. 12. Rutas: regex get %r{/hello/([w]+)} do "Hello, #{params[:captures].first}!" end get %r{/hello/([w]+)} do |c| "Hello, #{c}!" end
  13. 13. 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
  14. 14. 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'
  15. 15. Vistas ● Por defecto en /views ● Para usar otro directorio: set :views, File.dirname(__FILE__) + '/templates'
  16. 16. 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
  17. 17. 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
  18. 18. Plantillas inline get '/' do haml '%div.title Hello World' end
  19. 19. 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
  20. 20. Plantillas inline require 'rubygems' require 'sinatra' get '/' do haml :index end __END__ @@ layout %html = yield @@ index %div.title Hello world!!!!!
  21. 21. 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'
  22. 22. Pass get '/guess/:who' do pass unless params[:who] == 'Frank' 'You got me!' end get '/guess/*' do 'You missed!' end
  23. 23. 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
  24. 24. Más cosas ● Helpers ● Before flters ● Error handlers ● Code reloading ● HTTP caching (etag, last-modifed)
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. Deployment (ejemplo) Apache + Passenger confg.ru + public require 'yourapp' set :environment, :production run Sinatra::Application
  29. 29. Ejemplos de la VidaReal®
  30. 30. git-wiki LOCs Ruby: 220 http://github.com/sr/git-wiki Un wiki que usa git como backend
  31. 31. RifGraf LOCs Ruby: 60 http://github.com/adamwiggins/rifgraf Servicio web para recolección de datos y gráfcas
  32. 32. github-services LOCs Ruby: 117 (sin los servicios) http://github.com/pjhyett/github-services Service hooks para publicar commits
  33. 33. integrity http://integrityapp.com/ Servidor de integración continua
  34. 34. scanty http://github.com/adamwiggins/scanty/ Blog muy sencillo
  35. 35. panda http://github.com/newbamboo/panda Solución de video encoding y streaming sobre Amazon S3
  36. 36. 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
  37. 37. Rendimiento tinyurl.com/ruby-web-performance
  38. 38. Comparación en rendimiento
  39. 39. ¿Preguntas?
  40. 40. 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

×