SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
Ngoc Dao
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 

What's hot (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
 

Viewers also liked

High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010High Performance WordPress - WordCamp Jerusalem 2010
High Performance WordPress - WordCamp Jerusalem 2010
Barry Abrahamson
 

Viewers also liked (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...
 

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

Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01Sinatraonpassenger 090419090519 Phpapp01
Sinatraonpassenger 090419090519 Phpapp01
guestcaceba
 
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
Nobuo Danjou
 

Similar to 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
 

More from 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 Neo4j
Alberto 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
 

More from 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/...
 

Recently uploaded

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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?
 

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