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