一、安装
gem install sinatra
gem install thin rerun
sinatra 支持多种模板,建议选择内建的 erb 或安装 haml
gem install haml
二、Hello World 程序
-
require 'sinatra'
-
set :bind => '0.0.0.0' # 绑定到所有ip 地址
-
-
get '/' do
-
"Hello world, it's #{Time.now} at the server!"
-
end
运行: ruby hello_world.rb
浏览器就可以访问:
三、一些基础知识
路由 Routing :
四种基本的 http 访问请求
-
get '/dogs' do
-
# get a listing of all the dogs
-
end
-
-
get '/dog/:id' do
-
# just get one dog, you might find him like this:
-
@dog = Dog.find(params[:id])
-
# using the params convention, you specified in your route
-
end
-
-
post '/dog' do
-
# create a new dog listing
-
end
-
-
put '/dog/:id' do
-
# HTTP PUT request method to update an existing dog
-
end
-
-
delete '/dog/:id' do
-
# HTTP DELETE request method to remove a dog who
route 是 sinatra 的核心内容,更多请参考: 过滤器:Filters
Sinatra 提供了一种机制,可以让你将程序通过 链入 request 请求序列中。
Filters 定义了两个方法, before 和 after ,他们后面跟一个 block,用于执行特定任务。
before
The before method will let you pass a block to be evaluated before each and every route gets processed.
-
before do
-
MyStore.connect unless MyStore.connected?
-
end
-
-
get '/' do
-
@list = MyStore.find(:all)
-
erb :index
-
end
after
The after method lets you pass a block to be evaluated after each and every route gets processed.
-
after do
-
MyStore.disconnect
-
end
Pattern Matching
Filters optionally take a pattern to be matched against the requested URI during processing. Here’s a quick example you could use to run a contrived authenticate! method before accessing any “admin” type requests.
Handlers
Handlers are top-level methods available in Sinatra to take care of common HTTP routines. For instance there are handlers for and .
There are also handlers for redirection:
-
get '/' do
-
redirect '/someplace/else'
-
end
This will return a 302 HTTP Response to /someplace/else.
You can even use the Sinatra handler for sessions, just add this to your application or to a configure block:
Then you will be able to use the default cookie based session handler in your application:
-
get '/' do
-
session['counter'] ||= 0
-
session['counter'] += 1
-
"You've hit this page #{session['counter']} times!"
-
end
阅读(1059) | 评论(0) | 转发(0) |