1
0
Fork 0
mirror of https://github.com/sinatra/sinatra synced 2023-03-27 23:18:01 -04:00

Merge branch 'master' of git://github.com/sinatra/sinatra

This commit is contained in:
Vasily Polovnyov 2011-01-14 11:04:58 +03:00
commit 01c1448c81
20 changed files with 746 additions and 310 deletions

View file

@ -1,2 +1,3 @@
--readme README.rdoc
--title 'Sinatra API Documentation'
'lib/**/*.rb' - '*.rdoc'

22
CHANGES
View file

@ -6,7 +6,23 @@
* The `markaby` rendering method now allows passing a block, making inline
usage possible. Requires Tilt 1.2 or newer. (Konstantin Haase)
= 1.1.1 / Not Yet Released
* All render methods now take a `:layout_engine` option, allowing to use a
layout in a different template language. Even more useful than using this
directly (`erb :index, :layout_engine => :haml`) is setting this globally for
a template engine that otherwise does not support layouts, like Markdown or
Textile (`set :markdown, :layout_engine => :erb`). (Konstantin Haase)
* Before and after filters now support conditions, both with and without
patterns (`before '/api/*', :agent => /Songbird/`). (Konstantin Haase)
* `send_file` now allows overriding the Last-Modified header, which defaults
to the file's mtime, by passing a `:last_modified` option. (Konstantin Haase)
= 1.1.2 / 2010-10-25
Like 1.1.1, but with proper CHANGES file.
= 1.1.1 / 2010-10-25
* README has been translated to Russian (Nickolay Schwarz, Vasily Polovnyov)
and Portuguese (Luciano Sousa).
@ -34,6 +50,10 @@
* Headers set by cache_control now always set max_age as an Integer, making
sure it is compatible with RFC2616. (Konstantin Haase)
* Further improved handling of string encodings on Ruby 1.9, templates now
honor default_encoding and URLs support unicode characters. (Konstantin
Haase)
= 1.1.0 / 2010-10-24
* Before and after filters now support pattern matching, including the

View file

@ -177,7 +177,7 @@ Renderingmethoden rendern jeden String direkt.
Das haml gem wird benötigt, um Haml-Templates rendern zu können:
## haml muss eingebunden werden
# haml muss eingebunden werden
require 'haml'
get '/' do
@ -199,7 +199,7 @@ und individuell überschrieben werden.
=== Erb-Templates
## erb muss eingebunden werden
# erb muss eingebunden werden
require 'erb'
get '/' do
@ -212,7 +212,7 @@ Dieser Code rendert <tt>./views/index.erb</tt>.
Das erubis gem wird benötigt, um Erubis-Templates rendern zu können:
## erbubis muss eingebunden werden
# erbubis muss eingebunden werden
require 'erubis'
get '/' do
@ -225,7 +225,7 @@ Dieser Code rendert <tt>./views/index.erubis</tt>.
Das buidler gem wird benötigt, um Builder-Templates rendern zu können:
## builder muss eingebunden werden
# builder muss eingebunden werden
require 'builder'
get '/' do
@ -238,7 +238,7 @@ Dieser Code rendert <tt>./views/index.builder</tt>.
Das nokogiri gem wird benötigt, um Nokogiri-Templates rendern zu können:
## nokogiri muss eingebunden werden
# nokogiri muss eingebunden werden
require 'nokogiri'
get '/' do
@ -251,7 +251,7 @@ Dieser Code rendert <tt>./views/index.nokogiri</tt>.
Das haml gem wird benötigt, um SASS-Templates rendern zu können:
## sass muss eingebunden werden
# sass muss eingebunden werden
require 'sass'
get '/stylesheet.css' do
@ -275,7 +275,7 @@ und individuell überschrieben werden.
Das haml gem wird benötigt, um SCSS-Templates rendern zu können:
## sass muss eingebunden werden
# sass muss eingebunden werden
require 'sass'
get '/stylesheet.css' do
@ -299,7 +299,7 @@ und individuell überschrieben werden.
Das less gem wird benötigt, um Less-Templates rendern zu können:
## less muss eingebunden werden
# less muss eingebunden werden
require 'less'
get '/stylesheet.css' do
@ -312,7 +312,7 @@ Dieser Code rendert <tt>./views/stylesheet.less</tt>.
Das liquid gem wird benötigt, um Liquid-Templates rendern zu können:
## liquid muss eingebunden werden
# liquid muss eingebunden werden
require 'liquid'
get '/' do
@ -330,7 +330,7 @@ aufrufen kann, will man nahezu in allen Fällen +locals+ übergeben:
Das rdiscount gem wird benötigt, um Markdown-Templates rendern zu können:
## rdiscount muss eingebunden werden
# rdiscount muss eingebunden werden
require "rdiscount"
get '/' do
@ -356,7 +356,7 @@ aufzurufen:
Das RedCloth gem wird benötigt, um Textile-Templates rendern zu können:
## redcloth muss eingebunden werden
# redcloth muss eingebunden werden
require "redcloth"
get '/' do
@ -381,7 +381,7 @@ aufzurufen:
Das rdoc gem wird benötigt, um RDoc-Templates rendern zu können:
## RDoc muss eingebunden werden
# RDoc muss eingebunden werden
require "rdoc"
get '/' do
@ -406,7 +406,7 @@ aufzurufen:
Das radius gem wird benötigt, um Radius-Templates rendern zu können:
## radius muss eingebunden werden
# radius muss eingebunden werden
require 'radius'
get '/' do
@ -424,7 +424,7 @@ aufrufen kann, will man nahezu in allen Fällen +locals+ übergeben:
Das markaby gem wird benötigt, um Markaby-Templates rendern zu können:
## markaby muss eingebunden werden
# markaby muss eingebunden werden
require 'markaby'
get '/' do
@ -437,7 +437,7 @@ Dieser Code rendert <tt>./views/index.mab</tt>.
Das slim gem wird benötigt, um Slim-Templates rendern zu können:
## slim muss eingebunden werden
# slim muss eingebunden werden
require 'slim'
get '/' do
@ -450,7 +450,7 @@ Dieser Code rendert <tt>./views/index.slim</tt>.
Das coffee-script gem und das `coffee`-Programm werden benötigt, um CoffeScript-Templates rendern zu können:
## coffee-script muss eingebunden werden
# coffee-script muss eingebunden werden
require 'coffee-script'
get '/application.js' do

View file

@ -39,6 +39,11 @@ Cada ruta se asocia con un bloque:
.. aniquilar algo ..
end
options '/' do
.. informar algo ..
end
Las rutas son comparadas en el orden en el que son definidas. La primer ruta
que coincide con la petición es invocada.
@ -146,7 +151,7 @@ De esa manera podemos, por ejemplo, implementar fácilmente un streaming:
get('/') { Stream.new }
== Archivos estáticos
== Archivos Estáticos
Los archivos estáticos son servidos desde el directorio público
<tt>./public</tt>. Podés especificar una ubicación diferente ajustando la
@ -173,9 +178,9 @@ les pase como argumento.
=== Plantillas Haml
La gem/librería haml es necesaria para para renderizar plantillas HAML:
La gem/librería <tt>haml</tt> es necesaria para para renderizar plantillas HAML:
## Vas a necesitar requerir haml en tu app
# Vas a necesitar requerir haml en tu app
require 'haml'
get '/' do
@ -197,7 +202,7 @@ y reemplazadas individualmente.
=== Plantillas Erb
## Vas a necesitar requerir erb en tu app
# Vas a necesitar requerir erb en tu app
require 'erb'
get '/' do
@ -206,24 +211,36 @@ y reemplazadas individualmente.
Renderiza <tt>./views/index.erb</tt>
=== Erubis
=== Plantillas Erubis
La gem/librería erubis es necesaria para renderizar plantillas erubis:
La gem/librería <tt>erubis</tt> es necesaria para renderizar plantillas Erubis:
## Vas a necesitar requerir erubis en tu app
# Vas a necesitar requerir erubis en tu app
require 'erubis'
get '/' do
erubis :index
end
Renderiza <tt>./views/index.erubis</tt>
Renderiza <tt>./views/index.erubis</tt>.
También es posible reemplazar Erb con Erubis:
require 'erubis'
Tilt.register :erb, Tilt[:erubis]
get '/' do
erb :index
end
Renderiza <tt>./views/index.erb</tt> con Erubis.
=== Plantillas Builder
La gem/librería builder es necesaria para renderizar plantillas builder:
La gem/librería <tt>builder</tt> es necesaria para renderizar plantillas
builder:
## Vas a necesitar requerir builder en tu app
# Vas a necesitar requerir builder en tu app
require 'builder'
get '/' do
@ -234,9 +251,10 @@ Renderiza <tt>./views/index.builder</tt>.
=== Plantillas Nokogiri
La gem/librería nokogiri es necesaria para renderizar plantillas nokogiri:
La gem/librería <tt>nokogiri</tt> es necesaria para renderizar plantillas
nokogiri:
## Vas a necesitar requerir nokogiri en tu app
# Vas a necesitar requerir nokogiri en tu app
require 'nokogiri'
get '/' do
@ -247,9 +265,10 @@ Renderiza <tt>./views/index.nokogiri</tt>.
=== Plantillas Sass
La gem/librería haml es necesaria para renderizar plantillas Sass:
La gem/librería <tt>haml</tt> o <tt>sass</tt> es necesaria para renderizar
plantillas Sass:
## Vas a necesitar requerir haml o sass en tu app
# Vas a necesitar requerir haml o sass en tu app
require 'sass'
get '/stylesheet.css' do
@ -271,9 +290,10 @@ y reemplazadas individualmente.
=== Plantillas Scss
La gem/librería haml es necesaria para renderizar plantillas Scss:
La gem/librería <tt>haml</tt> o <tt>sass</tt>es necesaria para renderizar
plantillas Scss:
## Vas a necesitar requerir haml o sass en tu app
# Vas a necesitar requerir haml o sass en tu app
require 'sass'
get '/stylesheet.css' do
@ -295,9 +315,9 @@ y reemplazadas individualmente.
=== Plantillas Less
La gem/librería less es necesaria para renderizar plantillas Less:
La gem/librería <tt>less</tt> es necesaria para renderizar plantillas Less:
## Vas a necesitar requerir less en tu app
# Vas a necesitar requerir less en tu app
require 'less'
get '/stylesheet.css' do
@ -308,9 +328,9 @@ Renderiza <tt>./views/stylesheet.less</tt>.
=== Plantillas Liquid
La gem/librería liquid es necesaria para renderizar plantillas Liquid:
La gem/librería <tt>liquid</tt> es necesaria para renderizar plantillas Liquid:
## Vas a necesitar requerir liquid en tu app
# Vas a necesitar requerir liquid en tu app
require 'liquid'
get '/' do
@ -326,9 +346,10 @@ plantilla Liquid, casi siempre vas a querer pasarle locales:
=== Plantillas Markdown
La gem/librería rdiscount es necesaria para renderizar plantillas Markdown:
La gem/librería <tt>rdiscount</tt> es necesaria para renderizar plantillas
Markdown:
## Vas a necesitar requerir rdiscount en tu app
# Vas a necesitar requerir rdiscount en tu app
require "rdiscount"
get '/' do
@ -343,17 +364,53 @@ generalmente vas a usarlo en combinación con otro motor de renderizado:
erb :resumen, :locals => { :texto => markdown(:introduccion) }
Tené en cuenta que también podés llamar al método markdown desde otras
Tené en cuenta que también podés llamar al método +markdown+ desde otras
plantillas:
%h1 Hola Desde Haml!
%p= markdown(:saludos)
=== Plantilla Textile
Como no podés utilizar Ruby desde Markdown, no podés usar layouts escritos en
Markdown. De todos modos, es posible usar un motor de renderizado para el
layout distinto al de la plantilla pasando la opción `:layout_engine`:
La gem/librería RedCloth es necesaria para renderizar plantillas Textile:
get '/' do
markdown :index, :layout_engine => :erb
end
## Vas a necesitar requerir redcloth en tu app
Renderiza <tt>./views/index.md</tt> con el layout <tt>./views/layout.erb</tt>.
Recordá que podés asignar las opciones de renderizado globalmente:
set :markdown, :layout_engine => :haml, :layout => :post
get '/' do
markdown :index
end
Renderiza <tt>./views/index.md</tt> (o cualquier otra plantilla Markdown) con
el layout <tt>./views/post.haml</tt>.
También es posible parsear Markdown con BlueCloth en lugar de RDiscount:
require 'bluecloth'
Tilt.register 'markdown', BlueClothTemplate
Tilt.register 'mkd', BlueClothTemplate
Tilt.register 'md', BlueClothTemplate
get '/' do
markdown :index
end
Renderiza <tt>./views/index.md</tt> con BlueCloth.
=== Plantillas Textile
La gem/librería <tt>RedCloth</tt> es necesaria para renderizar plantillas
Textile:
# Vas a necesitar requerir redcloth en tu app
require "redcloth"
get '/' do
@ -367,17 +424,39 @@ generalmente vas a usarlo en combinación con otro motor de renderizado:
erb :resumen, :locals => { :texto => textile(:introduccion) }
Tené en cuenta que también podés llamar al método textile desde otras
Tené en cuenta que también podés llamar al método +textile+ desde otras
plantillas:
%h1 Hola Desde Haml!
%p= textile(:saludos)
Como no podés utilizar Ruby desde Textile, no podés usar layouts escritos en
Textile. De todos modos, es posible usar un motor de renderizado para el
layout distinto al de la plantilla pasando la opción `:layout_engine`:
get '/' do
textile :index, :layout_engine => :erb
end
Renderiza <tt>./views/index.textile</tt> con el layout
<tt>./views/layout.erb</tt>.
Recordá que podés asignar las opciones de renderizado globalmente:
set :textile, :layout_engine => :haml, :layout => :post
get '/' do
textile :index
end
Renderiza <tt>./views/index.textile</tt> (o cualquier otra plantilla Textile)
con el layout <tt>./views/post.haml</tt>.
=== Plantillas RDoc
La gem/librería RDoc es necesaria para renderizar plantillas RDoc:
La gem/librería <tt>rdoc</tt> es necesaria para renderizar plantillas RDoc:
## Vas a necesitar requerir rdoc en tu app
# Vas a necesitar requerir rdoc en tu app
require "rdoc"
get '/' do
@ -391,17 +470,38 @@ generalmente vas a usarlo en combinación con otro motor de renderizado:
erb :resumen, :locals => { :texto => rdoc(:introduccion) }
Tené en cuenta que también podés llamar al método rdoc desde otras
Tené en cuenta que también podés llamar al método +rdoc+ desde otras
plantillas:
%h1 Hola Desde Haml!
%p= rdoc(:saludos)
Como no podés utilizar Ruby desde RDoc, no podés usar layouts escritos en RDoc.
De todos modos, es posible usar un motor de renderizado para el layout distinto
al de la plantilla pasando la opción `:layout_engine`:
get '/' do
rdoc :index, :layout_engine => :erb
end
Renderiza <tt>./views/index.rdoc</tt> con el layout <tt>./views/layout.erb</tt>.
Recordá que podés asignar las opciones de renderizado globalmente:
set :rdoc, :layout_engine => :haml, :layout => :post
get '/' do
rdoc :index
end
Renderiza <tt>./views/index.rdoc</tt> (o cualquier otra plantilla RDoc) con el
layout <tt>./views/post.haml</tt>.
=== Plantillas Radius
La gem/librería radius es necesaria para renderizar plantillas Radius:
La gem/librería <tt>radius</tt> es necesaria para renderizar plantillas Radius:
## Vas a necesitar requerir radius en tu app
# Vas a necesitar requerir radius en tu app
require 'radius'
get '/' do
@ -417,9 +517,10 @@ plantilla Radius, casi siempre vas a querer pasarle locales:
=== Plantillas Markaby
La gem/librería markaby es necesaria para renderizar plantillas Markaby:
La gem/librería <tt>markaby</tt> es necesaria para renderizar plantillas
Markaby:
## Vas a necesitar requerir markaby en tu app
# Vas a necesitar requerir markaby en tu app
require 'markaby'
get '/' do
@ -428,11 +529,18 @@ La gem/librería markaby es necesaria para renderizar plantillas Markaby:
Renderiza <tt>./views/index.mab</tt>.
También podés usar Markaby inline:
get '/' do
markaby { h1 "Bienvenido!" }
end
=== Plantillas Slim
La gem/librería slim es necesaria para renderizar plantillas Slim:
La gem/librería <tt>slim</tt> es necesaria para renderizar plantillas Slim:
## Vas a necesitar requerir slim en tu app
# Vas a necesitar requerir slim en tu app
require 'slim'
get '/' do
@ -443,10 +551,16 @@ Renderiza <tt>./views/index.slim</tt>.
=== Plantillas CoffeeScript
La gem/librería coffee-script y el binario `coffee` son necesarios para
renderizar plantillas CoffeeScript:
La gem/librería <tt>coffee-script</tt> y al menos <b>una</b> de las siguientes
opciones para ejecutar JavaScript:
## Vas a necesitar requerir coffee-script en tu app
* +node+ (de Node.js) en tu path
* utilizar OSX
* la gem/librería +therubyracer+
son necesarios para renderizar plantillas CoffeeScript:
# Vas a necesitar requerir coffee-script en tu app
require 'coffee-script'
get '/application.js' do
@ -455,13 +569,13 @@ renderizar plantillas CoffeeScript:
Renderiza <tt>./views/application.coffee</tt>.
=== Plantillas Inline
=== Plantillas Embebidas
get '/' do
haml '%div.titulo Hola Mundo'
end
Renderiza el template contenido en el string.
Renderiza el template embebido en el string.
=== Accediendo a Variables en Plantillas
@ -527,13 +641,39 @@ Las plantillas también pueden ser definidas usando el método top-level
end
Si existe una plantilla con el nombre "layout", va a ser usada cada vez que
una plantilla es renderizada. Podés desactivar los layouts pasando
<tt>:layout => false</tt>.
una plantilla es renderizada. Podés desactivar los layouts individualmente
pasando <tt>:layout => false</tt> o globalmente con
<tt>set :haml, :layout => false</tt>.
get '/' do
haml :index, :layout => !request.xhr?
end
=== Asociando Extensiones de Archivo
Para asociar una extensión de archivo con un motor de renderizado, usá
<tt>Tilt.register</tt>. Por ejemplo, si querés usar la extensión +tt+ para
las plantillas Textile, podés hacer lo siguiente:
Tilt.register :tt, Tilt[:textile]
=== Agregando Tu Propio Motor de Renderizado
Primero, registrá tu motor con Tilt, y después, creá tu método de renderizado:
Tilt.register :mipg, MiMotorParaPlantillaGenial
helpers do
def mypg(*args) render(:mypg, *args) end
end
get '/' do
mypg :index
end
Renderiza <tt>./views/index.mypg</tt>. Mirá https://github.com/rtomayko/tilt
para aprender más de Tilt.
== Ayudantes
Usá el método top-level <tt>helpers</tt> para definir métodos ayudantes que
@ -587,6 +727,16 @@ patrón:
session[:ultimo_slug] = slug
end
Al igual que las rutas, los filtros también aceptan condiciones:
before :agent => /Songbird/ do
# ...
end
after '/blog/*', :host_name => 'ejemplo.com' do
# ...
end
== Interrupción
Para detener inmediatamente una petición dentro de un filtro o una ruta usá:
@ -696,7 +846,7 @@ Ejecutar cuando el entorno es <tt>:production</tt> o <tt>:test</tt>:
...
end
== Manejo de errores
== Manejo de Errores
Los manejadores de errores se ejecutan dentro del mismo contexto que las rutas
y los filtros before, lo que significa que podés usar, por ejemplo,
@ -862,13 +1012,6 @@ etc.). Ahí es donde Sinatra::Base entra en el juego:
end
end
La clase MiApp es un componente Rack independiente que puede actuar como Rack
middleware, una aplicación Rack, o Rails metal. Podés usar (con +use+) o
ejecutar (con +run+) esta clase desde un archivo rackup +config.ru+; o,
controlar un componente de servidor provisto como una librería:
MiApp.run! :host => 'localhost', :port => 9090
Las subclases de Sinatra::Base tienen disponibles exactamente los mismos
métodos que los provistos por el DSL de top-level. La mayoría de las
aplicaciones top-level se pueden convertir en componentes Sinatra::Base con
@ -885,6 +1028,64 @@ desactivadas por defecto, incluyendo el servidor incorporado. Mirá
{Opciones y Configuraciones}[http://sinatra.github.com/configuration.html]
para detalles sobre las opciones disponibles y su comportamiento.
=== Sirviendo una Aplicación Modular
Las dos opciones más comunes para iniciar una aplicación modular son, iniciarla
activamente con <tt>run!</tt>:
# mi_app.rb
require 'sinatra/base'
class MiApp < Sinatra::Base
# ... código de la app ...
# iniciar el servidor si el archivo fue ejecutado directamente
run! if app_file == $0
end
Iniciar con:
ruby mi_app.rb
O, con un archivo <tt>config.ru</tt>, que permite usar cualquier handler Rack:
# config.ru
require 'mi_app'
run MiApp
Después ejecutar:
rackup -p 4567
=== Usando una Aplicación Clásica con un Archivo config.ru
Escribí el archivo de tu aplicación:
# app.rb
require 'sinatra'
get '/' do
'Hola mundo!'
end
Y el <tt>config.ru</tt> correspondiente:
require 'app'
run Sinatra::Application
=== ¿Cuándo Usar config.ru?
Indicadores de que probablemente querés usar <tt>config.ru</tt>:
* Querés realizar el deploy con un hanlder Rack distinto (Passenger, Unicorn,
Heroku, ...).
* Querés usar más de una subclase de <tt>Sinatra::Base</tt>.
* Querés usar Sinatra únicamente para middleware, pero no como un endpoint.
<b>No hay necesidad de utilizar un archivo <tt>config.ru</tt> exclusivamente
porque tenés una aplicación modular, y no necesitás una aplicación modular para
iniciarla con <tt>config.ru</tt>.</b>
=== Utilizando Sinatra como Middleware
Sinatra no solo es capaz de usar otro Rack middleware, sino que a su vez,
@ -894,7 +1095,7 @@ aplicación basada en Rack (Rails/Ramaze/Camping/...).
require 'sinatra/base'
class PantallaDeLogin< Sinatra::Base
class PantallaDeLogin < Sinatra::Base
enable :sessions
get('/login') { haml :login }
@ -984,7 +1185,7 @@ desde el ámbito de la petición utilizando `settings`:
Tenés la ligadura al ámbito de la petición dentro de:
* bloques pasados a get/head/post/put/delete
* bloques pasados a get/head/post/put/delete/options
* filtros before/after
* métodos ayudantes
* plantillas/vistas
@ -1007,7 +1208,7 @@ Pegale una mirada al código: acá está el
{Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
que es {incluido en el espacio de nombres principal}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28].
== Línea de comandos
== Línea de Comandos
Las aplicaciones Sinatra pueden ser ejecutadas directamente:
@ -1022,33 +1223,71 @@ Las opciones son:
-s # especifica el servidor/manejador rack (thin es usado por defecto)
-x # activa el mutex lock (está desactivado por defecto)
== A la vanguardia
== A la Vanguardia
Si querés usar el código de Sinatra más reciente, cloná el repositorio
localmente y ejecutá tu aplicación, asegurándote que el directorio
<tt>sinatra/lib</tt> esté en el <tt>LOAD_PATH</tt>:
Si querés usar el código de Sinatra más reciente, sentite libre de ejecutar
tu aplicación sobre la rama master, en general es bastante estable.
También liberamos prereleases de vez en cuando, así, podés hacer
gem install sinatra --pre
Para obtener algunas de las últimas características.
=== Con Bundler
Esta es la manera recomendada para ejecutar tu aplicación sobre la última
versión de Sinatra usando {Bundler}[http://gembundler.com/].
Primero, instalá bundler si no lo hiciste todavía:
gem install bundler
Después, en el directorio de tu proyecto, creá un archivo +Gemfile+:
source :rubygems
gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git"
# otras dependencias
gem 'haml' # por ejemplo, si usás haml
gem 'activerecord', '~> 3.0' # quizás también necesités ActiveRecord 3.x
Tené en cuenta que tenés que listar todas las dependencias directas de tu
aplicación. No es necesario listar las dependencias de Sinatra (Rack y Tilt)
porque Bundler las agrega directamente.
Ahora podés arrancar tu aplicación así:
bundle exec ruby miapp.rb
=== Con Git
Cloná el repositorio localmente y ejecutá tu aplicación, asegurándote que el
directorio <tt>sinatra/lib</tt> esté en el <tt>LOAD_PATH</tt>:
cd miapp
git clone git://github.com/sinatra/sinatra.git
ruby -Isinatra/lib miapp.rb
Otra opción consiste en agregar el directorio <tt>sinatra/lib</tt> al
<tt>LOAD_PATH</tt> dentro de tu aplicación:
$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
require 'rubygems'
require 'sinatra'
get '/acerca-de' do
"Estoy usando la versión " + Sinatra::VERSION
end
Para actualizar el código fuente de Sinatra en el futuro:
cd miproyecto/sinatra
cd miapp/sinatra
git pull
== Más
=== Instalación Global
Podés construir la gem vos mismo:
git clone git://github.com/sinatra/sinatra.git
cd sinatra
rake sinatra.gemspec
rake install
Si instalás tus gems como root, el último paso debería ser
sudo rake install
== Lecturas Recomendadas
* {Sito web del proyecto}[http://www.sinatrarb.com/] - Documentación
adicional, noticias, y enlaces a otros recursos.

View file

@ -171,7 +171,7 @@ au lieu de les considérer comme un chemin vers un fichier.
Le gem haml est nécessaire pour utiliser la fonction de rendu Haml:
## Chargez la bibliothèque haml dans votre application
# Chargez la bibliothèque haml dans votre application
require 'haml'
get '/' do
@ -194,7 +194,7 @@ et supportent aussi la réécriture (surcharge) comme dans cet exemple.
=== Templates Erb
## Chargez la bibliothèque erb dans votre application
# Chargez la bibliothèque erb dans votre application
require 'erb'
get '/' do
@ -207,7 +207,7 @@ Utilisera le template: <tt>./views/index.erb</tt>
Le gem erubis est nécessaire pour utiliser la fonction de rendu erubis:
## Chargez la bibliothèque erubis dans votre application
# Chargez la bibliothèque erubis dans votre application
require 'erubis'
get '/' do
@ -220,7 +220,7 @@ Utilisera le template: <tt>./views/index.erubis</tt>
Le gem builder est nécessaire pour utiliser la fonction de rendu builder:
## Chargez la bibliothèque builder dans votre application
# Chargez la bibliothèque builder dans votre application
require 'builder'
get '/' do
@ -233,7 +233,7 @@ Utilisera le template: <tt>./views/index.builder</tt>.
Le gem nokogiri est nécessaire pour utiliser la fonction de rendu nokogiri:
## Chargez la bibliothèque nokogiri dans votre application
# Chargez la bibliothèque nokogiri dans votre application
require 'nokogiri'
get '/' do
@ -246,7 +246,7 @@ Utilisera le template: <tt>./views/index.nokogiri</tt>.
Le gem haml est nécessaire pour utiliser la fonction de rendu Sass:
## Chargez la bibliothèque haml ou sass dans votre application
# Chargez la bibliothèque haml ou sass dans votre application
require 'sass'
get '/stylesheet.css' do
@ -270,7 +270,7 @@ et supportent aussi la réécriture (surcharge) comme dans cet exemple.
Le gem haml est nécessaire pour utiliser la fonction de rendu Scss:
## Chargez la bibliothèque haml ou sass dans votre application
# Chargez la bibliothèque haml ou sass dans votre application
require 'sass'
get '/stylesheet.css' do
@ -294,7 +294,7 @@ et supportent aussi la réécriture (surcharge) comme dans cet exemple.
Le gem less est nécessaire pour utiliser la fonction de rendu Less:
## Chargez la bibliothèque less dans votre application
# Chargez la bibliothèque less dans votre application
require 'less'
get '/stylesheet.css' do
@ -307,7 +307,7 @@ Utilisera le template: <tt>./views/stylesheet.less</tt>.
Le gem liquid est nécessaire pour utiliser la fonction de rendu Liquid:
## Chargez la bibliothèque liquid dans votre application
# Chargez la bibliothèque liquid dans votre application
require 'liquid'
get '/' do
@ -325,7 +325,7 @@ template Liquid, il sera toujours nécessaire de lui passer des variables locale
Le gem rdiscount est nécessaire pour utiliser la fonction de rendu Markdown:
## Chargez la bibliothèque rdiscount dans votre application
# Chargez la bibliothèque rdiscount dans votre application
require "rdiscount"
get '/' do
@ -350,7 +350,7 @@ Notez que vous pouvez également appeler la méthode markdown au sein d'autres t
Le gem RedCloth est nécessaire pour utiliser la fonction de rendu Textile:
## Chargez la bibliothèqye redcloth dans votre application
# Chargez la bibliothèqye redcloth dans votre application
require "redcloth"
get '/' do
@ -374,7 +374,7 @@ Notez que vous pouvez également appeler la méthode textile au sein d'autres te
Le gem RDoc est nécessaire pour utiliser la fonction de rendu RDoc:
## Chargez la bibliothèque rdoc dans votre application
# Chargez la bibliothèque rdoc dans votre application
require "rdoc"
get '/' do
@ -398,7 +398,7 @@ Notez que vous pouvez également appeler la méthode rdoc au sein d'autres templ
Le gem radius est nécessaire pour utiliser la fonction de rendu Radius:
## Chargez la bibliotèque radius dans votre application
# Chargez la bibliotèque radius dans votre application
require 'radius'
get '/' do
@ -416,7 +416,7 @@ template Radius, il sera toujours nécessaire de lui passer des variables locale
Le gem markaby est nécessaire pour utiliser la fonction de rendu Markaby:
## Chargez la bibliothèque markaby dans votre application
# Chargez la bibliothèque markaby dans votre application
require 'markaby'
get '/' do
@ -429,7 +429,7 @@ Utilisera <tt>./views/index.mab</tt>.
Le gem slim est nécessaire pour utiliser la fonction de rendu Slim:
## Chargez la bibliothèque slim dans votre application
# Chargez la bibliothèque slim dans votre application
require 'slim'
get '/' do
@ -443,7 +443,7 @@ Utilisera <tt>./views/index.slim</tt>.
Le gem coffee-script et l'exécutable `coffee` sont nécessaires pour utiliser la
fonction de rendu CoffeeScript:
## Chargez la bibliothèque coffee-script dans votre application
# Chargez la bibliothèque coffee-script dans votre application
require 'coffee-script'
get '/application.js' do

View file

@ -123,7 +123,7 @@ metódusok minden, nekik közvetlenül átadott karakterláncot megjelenítenek.
HAML sablonok rendereléséhez szükségünk lesz a haml gem-re vagy könyvtárra:
## Importáljuk be a haml-t az alkalmazásba
# Importáljuk be a haml-t az alkalmazásba
require 'haml'
get '/' do
@ -146,7 +146,7 @@ A globális beállításokat lehetőségünk van felülírni metódus szinten is
=== Erb sablonok
## Importáljuk be az erb-t az alkalmazásba
# Importáljuk be az erb-t az alkalmazásba
require 'erb'
get '/' do
@ -160,7 +160,7 @@ Ez a <tt>./views/index.erb</tt> sablont fogja lerenderelni.
Szükségünk lesz a builder gem-re vagy könyvtárra a builder sablonok
rendereléséhez:
## Importáljuk be a builder-t az alkalmazásba
# Importáljuk be a builder-t az alkalmazásba
require 'builder'
get '/' do
@ -173,7 +173,7 @@ Ez pedig a <tt>./views/index.builder</tt> állományt fogja renderelni.
Sass sablonok használatához szükség lesz a haml gem-re vagy könyvtárra:
## Be kell importálni a haml, vagy a sass könyvtárat
# Be kell importálni a haml, vagy a sass könyvtárat
require 'sass'
get '/stylesheet.css' do

View file

@ -169,7 +169,7 @@ Rackレスポンス、Rackボディオブジェクト、HTTPステータスコ
hamlを使うにはhamlライブラリが必要です:
## hamlを読み込みます
# hamlを読み込みます
require 'haml'
get '/' do
@ -192,7 +192,7 @@ hamlを使うにはhamlライブラリが必要です:
=== Erb テンプレート
## erbを読み込みます
# erbを読み込みます
require 'erb'
get '/' do
@ -205,7 +205,7 @@ hamlを使うにはhamlライブラリが必要です:
erubisテンプレートを表示するには、erubisライブラリが必要です:
## erubisを読み込みます
# erubisを読み込みます
require 'erubis'
get '/' do
@ -218,7 +218,7 @@ erubisテンプレートを表示するには、erubisライブラリが必要
builderを使うにはbuilderライブラリが必要です:
## builderを読み込みます
# builderを読み込みます
require 'builder'
get '/' do
@ -231,7 +231,7 @@ builderを使うにはbuilderライブラリが必要です:
鋸を使うには鋸ライブラリが必要です:
## 鋸を読み込みます
# 鋸を読み込みます
require 'nokogiri'
get '/' do
@ -244,7 +244,7 @@ builderを使うにはbuilderライブラリが必要です:
Sassテンプレートを使うにはsassライブラリが必要です:
## hamlかsassを読み込みます
# hamlかsassを読み込みます
require 'sass'
get '/stylesheet.css' do
@ -268,7 +268,7 @@ see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
Scssテンプレートを使うにはsassライブラリが必要です:
## hamlかsassを読み込みます
# hamlかsassを読み込みます
require 'sass'
get '/stylesheet.css' do
@ -292,7 +292,7 @@ see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
Lessテンプレートを使うにはlessライブラリが必要です:
## lessを読み込みます
# lessを読み込みます
require 'less'
get '/stylesheet.css' do
@ -305,7 +305,7 @@ Lessテンプレートを使うにはlessライブラリが必要です:
Liquidテンプレートを使うにはliquidライブラリが必要です:
## liquidを読み込みます
# liquidを読み込みます
require 'liquid'
get '/' do
@ -323,7 +323,7 @@ LiquidテンプレートからRubyのメソッド(+yield+を除く)を呼び出
Markdownテンプレートを使うにはrdiscountライブラリが必要です:
## rdiscountを読み込みます
# rdiscountを読み込みます
require "rdiscount"
get '/' do
@ -346,7 +346,7 @@ markdownからメソッドを呼び出すことも、localsに変数を渡すこ
Textileテンプレートを使うにはRedClothライブラリが必要です:
## redclothを読み込みます
# redclothを読み込みます
require "redcloth"
get '/' do
@ -369,7 +369,7 @@ textileからメソッドを呼び出すことも、localsに変数を渡すこ
RDocテンプレートを使うにはRDocライブラリが必要です:
## rdocを読み込みます
# rdocを読み込みます
require "rdoc"
get '/' do
@ -392,7 +392,7 @@ rdocからメソッドを呼び出すことも、localsに変数を渡すこと
Radiusテンプレートを使うにはradiusライブラリが必要です:
## radiusを読み込みます
# radiusを読み込みます
require 'radius'
get '/' do
@ -410,7 +410,7 @@ RadiusテンプレートからRubyのメソッド(+yield+を除く)を呼び出
Markabyテンプレートを使うにはmarkabyライブラリが必要です:
## markabyを読み込みます
# markabyを読み込みます
require 'markaby'
get '/' do
@ -423,7 +423,7 @@ Markabyテンプレートを使うにはmarkabyライブラリが必要です:
Slimテンプレートを使うにはslimライブラリが必要です:
## slimを読み込みます
# slimを読み込みます
require 'slim'
get '/' do
@ -436,7 +436,7 @@ Slimテンプレートを使うにはslimライブラリが必要です:
CoffeeScriptテンプレートを表示するにはcoffee-scriptライブラリと`coffee`バイナリが必要です:
## coffee-scriptを読み込みます
# coffee-scriptを読み込みます
require 'coffee-script'
get '/application.js' do

View file

@ -119,7 +119,7 @@ qualquer string passada diretamente para elas.
A gem/biblioteca haml é necessária para renderizar templates HAML:
## Você precisa do 'require haml' em sua aplicação.
# Você precisa do 'require haml' em sua aplicação.
require 'haml'
get '/' do
@ -142,7 +142,7 @@ e substitua em uma requisição individual.
=== Erb Templates
## Você precisa do 'require erb' em sua aplicação
# Você precisa do 'require erb' em sua aplicação
require 'erb'
get '/' do
@ -155,7 +155,7 @@ Renderiza <tt>./views/index.erb</tt>
A gem/biblioteca erubis é necessária para renderizar templates erubis:
## Você precisa do 'require erubis' em sua aplicação.
# Você precisa do 'require erubis' em sua aplicação.
require 'erubis'
get '/' do
@ -168,7 +168,7 @@ Renderiza <tt>./views/index.erubis</tt>
A gem/biblioteca builder é necessária para renderizar templates builder:
## Você precisa do 'require builder' em sua aplicação.
# Você precisa do 'require builder' em sua aplicação.
require 'builder'
get '/' do
@ -182,7 +182,7 @@ Renderiza <tt>./views/index.builder</tt>.
A gem/biblioteca sass é necessária para renderizar templates sass:
## Você precisa do 'require haml' ou 'require sass' em sua aplicação.
# Você precisa do 'require haml' ou 'require sass' em sua aplicação.
require 'sass'
get '/stylesheet.css' do
@ -208,7 +208,7 @@ e substitua em uma requisição individual.
A gem/biblioteca less é necessária para renderizar templates Less:
## Você precisa do 'require less' em sua aplicação.
# Você precisa do 'require less' em sua aplicação.
require 'less'
get '/stylesheet.css' do

View file

@ -174,9 +174,9 @@ directly.
=== Haml Templates
The haml gem/library is required to render HAML templates:
The <tt>haml</tt> gem/library is required to render HAML templates:
## You'll need to require haml in your app
# You'll need to require haml in your app
require 'haml'
get '/' do
@ -199,33 +199,44 @@ and overridden on an individual basis.
=== Erb Templates
## You'll need to require erb in your app
# You'll need to require erb in your app
require 'erb'
get '/' do
erb :index
end
Renders <tt>./views/index.erb</tt>
Renders <tt>./views/index.erb</tt>.
=== Erubis
=== Erubis Templates
The erubis gem/library is required to render erubis templates:
The <tt>erubis</tt> gem/library is required to render Erubis templates:
## You'll need to require erubis in your app
# You'll need to require erubis in your app
require 'erubis'
get '/' do
erubis :index
end
Renders <tt>./views/index.erubis</tt>
Renders <tt>./views/index.erubis</tt>.
It is also possible to replace Erb with Erubis:
require 'erubis'
Tilt.register :erb, Tilt[:erubis]
get '/' do
erb :index
end
Renders <tt>./views/index.erb</tt> with Erubis.
=== Builder Templates
The builder gem/library is required to render builder templates:
The <tt>builder</tt> gem/library is required to render builder templates:
## You'll need to require builder in your app
# You'll need to require builder in your app
require 'builder'
get '/' do
@ -236,9 +247,9 @@ Renders <tt>./views/index.builder</tt>.
=== Nokogiri Templates
The nokogiri gem/library is required to render nokogiri templates:
The <tt>nokogiri</tt> gem/library is required to render nokogiri templates:
## You'll need to require nokogiri in your app
# You'll need to require nokogiri in your app
require 'nokogiri'
get '/' do
@ -249,9 +260,9 @@ Renders <tt>./views/index.nokogiri</tt>.
=== Sass Templates
The haml gem/library is required to render Sass templates:
The <tt>haml</tt> or <tt>sass</tt> gem/library is required to render Sass templates:
## You'll need to require haml or sass in your app
# You'll need to require haml or sass in your app
require 'sass'
get '/stylesheet.css' do
@ -273,9 +284,9 @@ and overridden on an individual basis.
=== Scss Templates
The haml gem/library is required to render Scss templates:
The <tt>haml</tt> or <tt>sass</tt> gem/library is required to render Scss templates:
## You'll need to require haml or sass in your app
# You'll need to require haml or sass in your app
require 'sass'
get '/stylesheet.css' do
@ -297,9 +308,9 @@ and overridden on an individual basis.
=== Less Templates
The less gem/library is required to render Less templates:
The <tt>less</tt> gem/library is required to render Less templates:
## You'll need to require less in your app
# You'll need to require less in your app
require 'less'
get '/stylesheet.css' do
@ -310,9 +321,9 @@ Renders <tt>./views/stylesheet.less</tt>.
=== Liquid Templates
The liquid gem/library is required to render Liquid templates:
The <tt>liquid</tt> gem/library is required to render Liquid templates:
## You'll need to require liquid in your app
# You'll need to require liquid in your app
require 'liquid'
get '/' do
@ -328,9 +339,9 @@ template, you almost always want to pass locals to it:
=== Markdown Templates
The rdiscount gem/library is required to render Markdown templates:
The <tt>rdiscount</tt> gem/library is required to render Markdown templates:
## You'll need to require rdiscount in your app
# You'll need to require rdiscount in your app
require "rdiscount"
get '/' do
@ -340,20 +351,58 @@ The rdiscount gem/library is required to render Markdown templates:
Renders <tt>./views/index.markdown</tt> (+md+ and +mkd+ are also valid file
extensions).
It is not possible to call methods from markdown, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
It is not possible to call methods from markdown, nor to pass locals to it.
You therefore will usually use it in combination with another rendering
engine:
erb :overview, :locals => { :text => markdown(:introduction) }
Note that you may also call the markdown method from within other templates:
Note that you may also call the +markdown+ method from within other templates:
%h1 Hello From Haml!
%p= markdown(:greetings)
Since you cannot call Ruby from Markdown, you cannot use layouts written in
Markdown. However, it is possible to use another rendering engine for the
template than for the layout by passing the `:layout_engine` option:
get '/' do
markdown :index, :layout_engine => :erb
end
This will render <tt>./views/index.md</tt> with <tt>./views/layout.erb</tt> as
layout.
Remember that you can set such rendering options globally:
set :markdown, :layout_engine => :haml, :layout => :post
get '/' do
markdown :index
end
This will render <tt>./views/index.md</tt> (and any other Markdown template)
with <tt>./views/post.haml</tt> as layout.
It is also possible to parse Markdown with BlueCloth rather than RDiscount:
require 'bluecloth'
Tilt.register 'markdown', BlueClothTemplate
Tilt.register 'mkd', BlueClothTemplate
Tilt.register 'md', BlueClothTemplate
get '/' do
markdown :index
end
Renders <tt>./views/index.md</tt> with BlueCloth.
=== Textile Templates
The RedCloth gem/library is required to render Textile templates:
The <tt>RedCloth</tt> gem/library is required to render Textile templates:
## You'll need to require redcloth in your app
# You'll need to require redcloth in your app
require "redcloth"
get '/' do
@ -362,20 +411,43 @@ The RedCloth gem/library is required to render Textile templates:
Renders <tt>./views/index.textile</tt>.
It is not possible to call methods from textile, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
It is not possible to call methods from textile, nor to pass locals to it. You
therefore will usually use it in combination with another rendering engine:
erb :overview, :locals => { :text => textile(:introduction) }
Note that you may also call the textile method from within other templates:
Note that you may also call the +textile+ method from within other templates:
%h1 Hello From Haml!
%p= textile(:greetings)
Since you cannot call Ruby from Textile, you cannot use layouts written in
Textile. However, it is possible to use another rendering engine for the
template than for the layout by passing the `:layout_engine` option:
get '/' do
textile :index, :layout_engine => :erb
end
This will render <tt>./views/index.textile</tt> with
<tt>./views/layout.erb</tt> as layout.
Remember that you can set such rendering options globally:
set :textile, :layout_engine => :haml, :layout => :post
get '/' do
textile :index
end
This will render <tt>./views/index.textile</tt> (and any other Textile
template) with <tt>./views/post.haml</tt> as layout.
=== RDoc Templates
The RDoc gem/library is required to render RDoc templates:
The <tt>rdoc</tt> gem/library is required to render RDoc templates:
## You'll need to require rdoc in your app
# You'll need to require rdoc in your app
require "rdoc"
get '/' do
@ -384,20 +456,43 @@ The RDoc gem/library is required to render RDoc templates:
Renders <tt>./views/index.rdoc</tt>.
It is not possible to call methods from rdoc, nor to pass locals to it. You therefore will usually use it in combination with another rendering engine:
It is not possible to call methods from rdoc, nor to pass locals to it. You
therefore will usually use it in combination with another rendering engine:
erb :overview, :locals => { :text => rdoc(:introduction) }
Note that you may also call the rdoc method from within other templates:
Note that you may also call the +rdoc+ method from within other templates:
%h1 Hello From Haml!
%p= rdoc(:greetings)
Since you cannot call Ruby from RDoc, you cannot use layouts written in
RDoc. However, it is possible to use another rendering engine for the
template than for the layout by passing the `:layout_engine` option:
get '/' do
rdoc :index, :layout_engine => :erb
end
This will render <tt>./views/index.rdoc</tt> with <tt>./views/layout.erb</tt> as
layout.
Remember that you can set such rendering options globally:
set :rdoc, :layout_engine => :haml, :layout => :post
get '/' do
rdoc :index
end
This will render <tt>./views/index.rdoc</tt> (and any other RDoc template)
with <tt>./views/post.haml</tt> as layout.
=== Radius Templates
The radius gem/library is required to render Radius templates:
The <tt>radius</tt> gem/library is required to render Radius templates:
## You'll need to require radius in your app
# You'll need to require radius in your app
require 'radius'
get '/' do
@ -413,9 +508,9 @@ template, you almost always want to pass locals to it:
=== Markaby Templates
The markaby gem/library is required to render Markaby templates:
The <tt>markaby</tt> gem/library is required to render Markaby templates:
## You'll need to require markaby in your app
# You'll need to require markaby in your app
require 'markaby'
get '/' do
@ -424,7 +519,7 @@ The markaby gem/library is required to render Markaby templates:
Renders <tt>./views/index.mab</tt>.
If you have Tilt 1.2 or later, you may also use inline markaby:
You may also use inline Markaby:
get '/' do
markaby { h1 "Welcome!" }
@ -432,9 +527,9 @@ If you have Tilt 1.2 or later, you may also use inline markaby:
=== Slim Templates
The slim gem/library is required to render Slim templates:
The <tt>slim</tt> gem/library is required to render Slim templates:
## You'll need to require slim in your app
# You'll need to require slim in your app
require 'slim'
get '/' do
@ -445,10 +540,18 @@ Renders <tt>./views/index.slim</tt>.
=== CoffeeScript Templates
The coffee-script gem/library and the `coffee` binary are required to render
CoffeeScript templates:
The <tt>coffee-script</tt> gem/library and at least <b>one</b> of the
following options to execute JavaScript:
## You'll need to require coffee-script in your app
* +node+ (from Node.js) in your path
* you must be running on OSX
* +therubyracer+ gem/library
See http://github.com/josh/ruby-coffee-script for an updated list of options.
Now you can render CoffeeScript templates:
# You'll need to require coffee-script in your app
require 'coffee-script'
get '/application.js' do
@ -457,13 +560,13 @@ CoffeeScript templates:
Renders <tt>./views/application.coffee</tt>.
=== Inline Templates
=== Embedded Templates
get '/' do
haml '%div.title Hello World'
end
Renders the inlined template string.
Renders the embedded template string.
=== Accessing Variables in Templates
@ -525,12 +628,38 @@ Templates may also be defined using the top-level <tt>template</tt> method:
end
If a template named "layout" exists, it will be used each time a template
is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
is rendered. You can individually disable layouts by passing <tt>:layout => false</tt>
or disable them by default via <tt>set :haml, :layout => false</tt>.
get '/' do
haml :index, :layout => !request.xhr?
end
=== Associating File Extensions
To associate a file extension with a template engine, use
<tt>Tilt.register</tt>. For instance, if you like to use the file extension
+tt+ for Textile templates, you can do the following:
Tilt.register :tt, Tilt[:textile]
=== Adding You Own Template Engine
First, register your engine with Tilt, then create a rendering method:
Tilt.register :myat, MyAwesomeTemplateEngine
helpers do
def myat(*args) render(:myat, *args) end
end
get '/' do
myat :index
end
Renders <tt>./views/index.myat</tt>. See https://github.com/rtomayko/tilt to
learn more about Tilt.
== Helpers
Use the top-level <tt>helpers</tt> method to define helper methods for use in
@ -698,7 +827,7 @@ Run when the environment is set to either <tt>:production</tt> or
...
end
== Error handling
== Error Handling
Error handlers run within the same context as routes and before filters, which
means you get all the goodies it has to offer, like <tt>haml</tt>,
@ -758,7 +887,7 @@ Or a range:
Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
running under the development environment.
== Mime types
== Mime Types
When using <tt>send_file</tt> or static files you may have mime types Sinatra
doesn't understand. Use +mime_type+ to register them by file extension:
@ -861,13 +990,6 @@ etc.). That's where Sinatra::Base comes into play:
end
end
The MyApp class is an independent Rack component that can act as
Rack middleware, a Rack application, or Rails metal. You can +use+ or
+run+ this class from a rackup +config.ru+ file; or, control a server
component shipped as a library:
MyApp.run! :host => 'localhost', :port => 9090
The methods available to Sinatra::Base subclasses are exactly as those
available via the top-level DSL. Most top-level apps can be converted to
Sinatra::Base components with two modifications:
@ -882,6 +1004,64 @@ Sinatra::Base components with two modifications:
including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
for details on available options and their behavior.
=== Serving a Modular Application
There are two common options for starting a modular app, activly starting with
<tt>run!</tt>:
# my_app.rb
require 'sinatra/base'
class MyApp < Sinatra::Base
# ... app code here ...
# start the server if ruby file executed directly
run! if app_file == $0
end
Start with:
ruby my_app.rb
Or with a <tt>config.ru</tt>, which allows using any Rack handler:
# config.ru
require 'my_app'
run MyApp
Run:
rackup -p 4567
=== Using a Classic Style Application with a config.ru
Write your app file:
# app.rb
require 'sinatra'
get '/' do
'Hello world!'
end
And a corresponding <tt>config.ru</tt>:
require 'app'
run Sinatra::Application
=== When to use a config.ru?
Good signs you probably want to use a <tt>config.ru</tt>:
* You want to deploy with a different Rack handler (Passenger, Unicorn,
Heroku, ...).
* You want to use more than one subclass of <tt>Sinatra::Base</tt>.
* You want to use Sinatra only for middleware, but not as endpoint.
<b>There is no need to switch to a <tt>config.ru</tt> only because you
switched to modular style, and you don't have to use modular style for running
with a <tt>config.ru</tt>.</b>
=== Using Sinatra as Middleware
Not only is Sinatra able to use other Rack middleware, any Sinatra application
@ -1004,7 +1184,7 @@ Have a look at the code for yourself: here's the
{Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128]
being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28].
== Command line
== Command Line
Sinatra applications can be run directly:
@ -1020,32 +1200,67 @@ Options are:
-x # turn on the mutex lock (default is off)
== The Bleeding Edge
If you would like to use Sinatra's latest bleeding code, feel free to run your
application against the master branch, it should be rather stable.
If you would like to use Sinatra's latest bleeding code, create a local
clone and run your app with the <tt>sinatra/lib</tt> directory on the
<tt>LOAD_PATH</tt>:
We also push out prerelease gems from time to time, so you can do a
gem install sinatra --pre
To get some of the latest features.
=== With Bundler
If you want to run your application with the latest Sinatra, using
{Bundler}[http://gembundler.com/] is the recommend way.
First, install bundler, if you haven't:
gem install bundler
Then, in you project directory, create a +Gemfile+:
source :rubygems
gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git"
# other dependencies
gem 'haml' # for instance, if you use haml
gem 'activerecord', '~> 3.0' # maybe you also need ActiveRecord 3.x
Note that you will have to list all your applications dependencies in there.
Sinatra's direct dependencies (Rack and Tilt) will however be automatically
fetched and added by Bundler.
Now you can run your app like this:
bundle exec ruby myapp.rb
=== Roll Your Own
Create a local clone and run your app with the <tt>sinatra/lib</tt> directory
on the <tt>LOAD_PATH</tt>:
cd myapp
git clone git://github.com/sinatra/sinatra.git
ruby -Isinatra/lib myapp.rb
Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
<tt>LOAD_PATH</tt> in your application:
$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
require 'rubygems'
require 'sinatra'
get '/about' do
"I'm running version " + Sinatra::VERSION
end
To update the Sinatra sources in the future:
cd myproject/sinatra
cd myapp/sinatra
git pull
== More
=== Install Globally
You can build the gem on your own:
git clone git://github.com/sinatra/sinatra.git
cd sinatra
rake sinatra.gemspec
rake install
If you install gems as root, the last step should be
sudo rake install
== Further Reading
* {Project Website}[http://www.sinatrarb.com/] - Additional documentation,
news, and links to other resources.

View file

@ -174,7 +174,7 @@ Sinatra — это предметно-ориентированный язык (D
Haml gem/библиотека необходима для рендеринга HAML шаблонов:
## Вам нужно будет подключить haml gem в приложении
# Вам нужно будет подключить haml gem в приложении
require 'haml'
get '/' do
@ -197,7 +197,7 @@ Haml gem/библиотека необходима для рендеринга H
=== Erb шаблоны
## Вам нужно будет подключить erb в приложении
# Вам нужно будет подключить erb в приложении
require 'erb'
get '/' do
@ -210,7 +210,7 @@ Haml gem/библиотека необходима для рендеринга H
Erubis gem/библиотека необходима для рендеринга erubis шаблонов:
## Вам нужно будет подключить erubis в приложении
# Вам нужно будет подключить erubis в приложении
require 'erubis'
get '/' do
@ -223,7 +223,7 @@ Erubis gem/библиотека необходима для рендеринга
Builder gem/библиотека необходима для рендеринга builder шаблонов:
## Вам нужно будет подключить builder в приложении
# Вам нужно будет подключить builder в приложении
require 'builder'
get '/' do
@ -236,7 +236,7 @@ Builder gem/библиотека необходима для рендеринг
Nokogiri gem/библиотека необходима для рендеринга nokogiri шаблонов:
## Вам нужно будет подключить nokogiri в приложении
# Вам нужно будет подключить nokogiri в приложении
require 'nokogiri'
get '/' do
@ -249,7 +249,7 @@ Nokogiri gem/библиотека необходима для рендеринг
Haml gem/библиотека необходима для рендеринга Sass шаблонов:
## Вам нужно будет подключить haml или sass в приложении
# Вам нужно будет подключить haml или sass в приложении
require 'sass'
get '/stylesheet.css' do
@ -273,7 +273,7 @@ Haml gem/библиотека необходима для рендеринга S
Haml gem/библиотека необходима для рендеринга Scss шаблонов:
## Вам нужно будет подключить haml или sass в приложении
# Вам нужно будет подключить haml или sass в приложении
require 'sass'
get '/stylesheet.css' do
@ -297,7 +297,7 @@ Haml gem/библиотека необходима для рендеринга S
less gem/библиотека необходима для рендеринга Less шаблонов:
## Вам нужно будет подключить less в приложении
# Вам нужно будет подключить less в приложении
require 'less'
get '/stylesheet.css' do
@ -310,7 +310,7 @@ less gem/библиотека необходима для рендеринга L
liquid gem/библиотека необходима для рендеринга liquid шаблонов:
## Вам нужно будет подключить liquid в приложении
# Вам нужно будет подключить liquid в приложении
require 'liquid'
get '/' do
@ -328,7 +328,7 @@ liquid gem/библиотека необходима для рендеринга
rdiscount gem/библиотека необходима для рендеринга Markdown шаблонов:
## Вам нужно будет подключить rdiscount в приложении
# Вам нужно будет подключить rdiscount в приложении
require "rdiscount"
get '/' do
@ -352,7 +352,7 @@ rdiscount gem/библиотека необходима для рендерин
RedCloth gem/библиотека необходима для рендеринга Textile шаблонов:
## Вам нужно будет подключить redcloth в приложении
# Вам нужно будет подключить redcloth в приложении
require "redcloth"
get '/' do
@ -375,7 +375,7 @@ RedCloth gem/библиотека необходима для рендеринг
RDoc gem/библиотека необходима для рендеринга RDoc шаблонов:
## Вам нужно будет подключить rdoc в приложении
# Вам нужно будет подключить rdoc в приложении
require "rdoc"
get '/' do
@ -398,7 +398,7 @@ RDoc gem/библиотека необходима для рендеринга R
radius gem/библиотека необходима для рендеринга Radius шаблонов:
## Вам нужно будет подключить radius в приложении
# Вам нужно будет подключить radius в приложении
require 'radius'
get '/' do
@ -416,7 +416,7 @@ radius gem/библиотека необходима для рендеринга
markaby gem/библиотека необходима для рендеринга Markaby шаблонов:
## Вам нужно будет подключить markaby в приложении
# Вам нужно будет подключить markaby в приложении
require 'markaby'
get '/' do
@ -436,7 +436,7 @@ markaby шаблоны:
slim gem/библиотека необходима для рендеринга slim шаблонов:
## Вам нужно будет подключить slim в приложении
# Вам нужно будет подключить slim в приложении
require 'slim'
get '/' do
@ -449,7 +449,7 @@ slim gem/библиотека необходима для рендеринга s
coffee-script gem/библиотека и `coffee` бинарный файл необходимы для рендеринга CoffeeScript шаблонов:
## Вам нужно будет подключить coffee-script в приложении
# Вам нужно будет подключить coffee-script в приложении
require 'coffee-script'
get '/application.js' do

View file

@ -172,7 +172,7 @@ Rack body对象或者HTTP状态码
需要引入haml gem/library以渲染 HAML 模板:
## 你需要在你的应用中引入 haml
# 你需要在你的应用中引入 haml
require 'haml'
get '/' do
@ -195,7 +195,7 @@ Rack body对象或者HTTP状态码
=== Erb模板
## 你需要在你的应用中引入 erb
# 你需要在你的应用中引入 erb
require 'erb'
get '/' do
@ -208,7 +208,7 @@ Rack body对象或者HTTP状态码
需要引入erubis gem/library以渲染 erubis 模板:
## 你需要在你的应用中引入 erubis
# 你需要在你的应用中引入 erubis
require 'erubis'
get '/' do
@ -221,7 +221,7 @@ Rack body对象或者HTTP状态码
需要引入 builder gem/library 以渲染 builder templates
## 需要在你的应用中引入builder
# 需要在你的应用中引入builder
require 'builder'
get '/' do
@ -234,7 +234,7 @@ Rack body对象或者HTTP状态码
需要引入 nokogiri gem/library 以渲染 nokogiri 模板:
## 需要在你的应用中引入 nokogiri
# 需要在你的应用中引入 nokogiri
require 'nokogiri'
get '/' do
@ -247,7 +247,7 @@ Rack body对象或者HTTP状态码
需要引入 haml gem/library 以渲染 Sass 模板:
## 需要在你的应用中引入 haml 或者 sass
# 需要在你的应用中引入 haml 或者 sass
require 'sass'
get '/stylesheet.css' do
@ -271,7 +271,7 @@ Rack body对象或者HTTP状态码
需要引入 haml gem/library 来渲染 Scss templates
## 需要在你的应用中引入 haml 或者 sass
# 需要在你的应用中引入 haml 或者 sass
require 'sass'
get '/stylesheet.css' do
@ -295,7 +295,7 @@ Rack body对象或者HTTP状态码
需要引入 less gem/library 以渲染 Less 模板:
## 需要在你的应用中引入 less
# 需要在你的应用中引入 less
require 'less'
get '/stylesheet.css' do
@ -308,7 +308,7 @@ Rack body对象或者HTTP状态码
需要引入 liquid gem/library 来渲染 Liquid 模板:
## 需要在你的应用中引入 liquid
# 需要在你的应用中引入 liquid
require 'liquid'
get '/' do
@ -326,7 +326,7 @@ Rack body对象或者HTTP状态码
需要引入 rdiscount gem/library 以渲染 Markdown 模板:
## 需要在你的应用中引入rdiscount
# 需要在你的应用中引入rdiscount
require "rdiscount"
get '/' do
@ -349,7 +349,7 @@ Rack body对象或者HTTP状态码
需要引入 RedCloth gem/library 以渲染 Textile 模板:
## 在你的应用中引入redcloth
# 在你的应用中引入redcloth
require "redcloth"
get '/' do
@ -371,7 +371,7 @@ Rack body对象或者HTTP状态码
需要引入 RDoc gem/library 以渲染RDoc模板
## 需要在你的应用中引入rdoc
# 需要在你的应用中引入rdoc
require "rdoc"
get '/' do
@ -393,7 +393,7 @@ Rack body对象或者HTTP状态码
需要引入 radius gem/library 以渲染 Radius 模板:
## You'll need to require radius in your app
# You'll need to require radius in your app
require 'radius'
get '/' do
@ -411,7 +411,7 @@ Rack body对象或者HTTP状态码
需要引入markaby gem/library以渲染Markaby模板
##需要在你的应用中引入 markaby
#需要在你的应用中引入 markaby
require 'markaby'
get '/' do
@ -424,7 +424,7 @@ Rack body对象或者HTTP状态码
需要引入 slim gem/library 来渲染 Slim 模板:
## 需要在你的应用中引入 slim
# 需要在你的应用中引入 slim
require 'slim'
get '/' do
@ -438,7 +438,7 @@ Rack body对象或者HTTP状态码
需要引入 coffee-script gem/library 并在路径中存在 `coffee` 二进制文件以渲染
CoffeeScript 模板:
## 需要在你的应用中引入coffee-script
# 需要在你的应用中引入coffee-script
require 'coffee-script'
get '/application.js' do

View file

@ -17,21 +17,11 @@ task :test do
ENV.delete 'LC_CTYPE'
end
if !ENV['NO_TEST_FIX'] and RUBY_VERSION == '1.9.2' and RUBY_PATCHLEVEL == 0
# Avoids seg fault
task(:test) do
second_run = %w[settings rdoc markaby templates static textile].map { |l| "test/#{l}_test.rb" }
first_run = Dir.glob('test/*_test.rb') - second_run
[first_run, second_run].each { |f| sh "testrb #{f.join ' '}" }
end
else
Rake::TestTask.new(:test) do |t|
Rake::TestTask.new(:test) do |t|
t.test_files = FileList['test/*_test.rb']
t.ruby_opts = ['-rubygems'] if defined? Gem
t.ruby_opts << '-I.'
end
end
# Rcov ================================================================
namespace :test do
desc 'Mesures test coverage'
@ -48,25 +38,7 @@ end
desc 'Generate RDoc under doc/api'
task 'doc' => ['doc:api']
task 'doc:api' => ['doc/api/index.html']
file 'doc/api/index.html' => FileList['lib/**/*.rb', 'README.*'] do |f|
require 'rbconfig'
hanna = RbConfig::CONFIG['ruby_install_name'].sub('ruby', 'hanna')
rb_files = f.prerequisites
sh(<<-end.gsub(/\s+/, ' '))
#{hanna}
--charset utf8
--fmt html
--inline-source
--line-numbers
--main README.rdoc
--op doc/api
--title 'Sinatra API Documentation'
#{rb_files.join(' ')}
end
end
task('doc:api') { sh "yardoc -o doc/api" }
CLEAN.include 'doc/api'
# README ===============================================================

View file

@ -7,7 +7,7 @@ require 'sinatra/showexceptions'
require 'tilt'
module Sinatra
VERSION = '1.2.0'
VERSION = '1.2.0.a'
# The request object. See Rack::Request for more info:
# http://rack.rubyforge.org/doc/classes/Rack/Request.html
@ -376,8 +376,6 @@ module Sinatra
attr_accessor :content_type
end
include Tilt::CompileSite
def erb(template, options={}, locals={})
render :erb, template, options, locals
end
@ -460,6 +458,7 @@ module Sinatra
# merge app-level options
options = settings.send(engine).merge(options) if settings.respond_to?(engine)
options[:outvar] ||= '@_out_buf'
options[:default_encoding] ||= settings.default_encoding
# extract generic options
locals = options.delete(:locals) || locals || {}

View file

@ -3,8 +3,8 @@ Gem::Specification.new do |s|
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.name = 'sinatra'
s.version = '1.2.0'
s.date = '2010-12-14'
s.version = '1.2.0.a'
s.date = '2010-12-25'
s.description = "Classy web-development dressed in a DSL"
s.summary = "Classy web-development dressed in a DSL"
@ -117,7 +117,7 @@ Gem::Specification.new do |s|
s.extra_rdoc_files = %w[README.rdoc README.de.rdoc README.jp.rdoc README.fr.rdoc README.es.rdoc README.hu.rdoc README.zh.rdoc LICENSE]
s.add_dependency 'rack', '~> 1.1'
s.add_dependency 'tilt', '~> 1.1'
s.add_dependency 'tilt', '~> 1.2'
s.add_development_dependency 'rake'
s.add_development_dependency 'shotgun', '~> 0.6'
s.add_development_dependency 'rack-test', '>= 0.5.6'
@ -130,7 +130,7 @@ Gem::Specification.new do |s|
s.add_development_dependency 'RedCloth'
s.add_development_dependency 'radius'
s.add_development_dependency 'markaby'
s.add_development_dependency 'coffee-script'
s.add_development_dependency 'coffee-script', '>= 2.0'
s.add_development_dependency 'rdoc'
s.add_development_dependency 'nokogiri'
s.add_development_dependency 'slim'

View file

@ -16,7 +16,7 @@ class CoffeeTest < Test::Unit::TestCase
it 'renders inline Coffee strings' do
coffee_app { coffee "alert 'Aye!'\n" }
assert ok?
assert_equal "(function() {\n alert('Aye!');\n})();\n", body
assert_equal "(function() {\n alert('Aye!');\n}).call(this);\n", body
end
it 'defaults content type to javascript' do
@ -45,13 +45,13 @@ class CoffeeTest < Test::Unit::TestCase
it 'renders .coffee files in views path' do
coffee_app { coffee :hello }
assert ok?
assert_equal "(function() {\n alert(\"Aye!\");\n})();\n", body
assert_equal "(function() {\n alert(\"Aye!\");\n}).call(this);\n", body
end
it 'ignores the layout option' do
coffee_app { coffee :hello, :layout => :layout2 }
assert ok?
assert_equal "(function() {\n alert(\"Aye!\");\n})();\n", body
assert_equal "(function() {\n alert(\"Aye!\");\n}).call(this);\n", body
end
it "raises error if template not found" do

View file

@ -53,6 +53,10 @@ class Test::Unit::TestCase
response.body.to_s
end
def assert_body(value)
assert_equal value.lstrip.gsub(/\s*\n\s*/, ""), body.lstrip.gsub(/\s*\n\s*/, "")
end
# Delegate other missing methods to response.
def method_missing(name, *args, &block)
if response && response.respond_to?(name)

View file

@ -12,13 +12,6 @@ class MarkabyTest < Test::Unit::TestCase
get '/'
end
def check_tilt(&block)
instance_eval(&block)
rescue TypeError => e
raise e unless Tilt::VERSION < '1.2'
warn "\nUpgrade Tilt!"
end
it 'renders inline markaby strings' do
markaby_app { markaby 'h1 "Hiya"' }
assert ok?
@ -48,15 +41,12 @@ class MarkabyTest < Test::Unit::TestCase
end
it 'renders inline markaby blocks' do
check_tilt do
markaby_app { markaby { h1 'Hiya' } }
assert ok?
assert_equal "<h1>Hiya</h1>", body
end
end
it 'renders inline markaby blocks with inline layouts' do
check_tilt do
markaby_app do
settings.layout { 'h1 { text "THIS. IS. "; yield }' }
markaby { em 'SPARTA' }
@ -64,15 +54,12 @@ class MarkabyTest < Test::Unit::TestCase
assert ok?
assert_equal "<h1>THIS. IS. <em>SPARTA</em></h1>", body
end
end
it 'renders inline markaby blocks with file layouts' do
check_tilt do
markaby_app { markaby(:layout => :layout2) { text "Hello World" } }
assert ok?
assert_equal "<h1>Markaby Layout!</h1><p>Hello World</p>", body
end
end
it "raises error if template not found" do
mock_app { get('/') { markaby :no_such_template } }

View file

@ -15,7 +15,7 @@ class NokogiriTest < Test::Unit::TestCase
it 'renders inline Nokogiri strings' do
nokogiri_app { nokogiri 'xml' }
assert ok?
assert_equal %{<?xml version="1.0"?>\n}, body
assert_body %{<?xml version="1.0"?>\n}
end
it 'renders inline blocks' do
@ -26,7 +26,7 @@ class NokogiriTest < Test::Unit::TestCase
end
end
assert ok?
assert_equal "<?xml version=\"1.0\"?>\n<couple>Frank &amp; Mary</couple>\n", body
assert_body "<?xml version=\"1.0\"?>\n<couple>Frank &amp; Mary</couple>\n"
end
it 'renders .nokogiri files in views path' do
@ -35,7 +35,7 @@ class NokogiriTest < Test::Unit::TestCase
nokogiri :hello
end
assert ok?
assert_equal %(<?xml version="1.0"?>\n<exclaim>You're my boy, Blue!</exclaim>\n), body
assert_body %(<?xml version="1.0"?>\n<exclaim>You're my boy, Blue!</exclaim>\n)
end
it "renders with inline layouts" do
@ -46,7 +46,7 @@ class NokogiriTest < Test::Unit::TestCase
end
get '/'
assert ok?
assert_equal "<?xml version=\"1.0\"?>\n<layout>\n <em>Hello World</em>\n</layout>\n", body
assert_body "<?xml version=\"1.0\"?>\n<layout>\n <em>Hello World</em>\n</layout>\n"
end
it "renders with file layouts" do
@ -56,7 +56,7 @@ class NokogiriTest < Test::Unit::TestCase
nokogiri %(xml.em 'Hello World'), :layout => :layout2
end
assert ok?
assert_equal "<?xml version=\"1.0\"?>\n<layout>\n <em>Hello World</em>\n</layout>\n", body
assert_body "<?xml version=\"1.0\"?>\n<layout>\n <em>Hello World</em>\n</layout>\n"
end
it "raises error if template not found" do

View file

@ -15,13 +15,13 @@ class RdocTest < Test::Unit::TestCase
it 'renders inline rdoc strings' do
rdoc_app { rdoc '= Hiya' }
assert ok?
assert_equal "<h1>Hiya</h1>\n", body
assert_body "<h1>Hiya</h1>"
end
it 'renders .rdoc files in views path' do
rdoc_app { rdoc :hello }
assert ok?
assert_equal "<h1>Hello From RDoc</h1>\n", body
assert_body "<h1>Hello From RDoc</h1>"
end
it "raises error if template not found" do

View file

@ -5,7 +5,6 @@ File.delete(File.dirname(__FILE__) + '/views/layout.test') rescue nil
class TestTemplate < Tilt::Template
def prepare
end
alias compile! prepare # for tilt < 0.7
def evaluate(scope, locals={}, &block)
inner = block ? block.call : ''