用 sinatra 也很长时间了,写一下文章分享一下使用方法. 例子在 https://github.com/towonzhou/sinatra-test
首先介绍一下 sinatra 和为什么使用 sinatra............(这种高度概括的东西不太好写,酝酿一段时间.) 如果你想做一个移动 app 的后台,那么 sinatra 将是一个很好的选择
##一。hello world!
gem install sinatra
require 'bundler/setup' require 'sinatra'
get '/' do "Hello world, it's #{Time.now} at the server!" end
搞定,保存.
3. 运行
`$> ruby hello_world.rb`
输出为:
Sinatra/1.4.4 has taken the stage on 4567 for development with backup from Thin Thin web server (v1.6.2 codename Doc Brown) Maximum connections set to 1024 Listening on localhost:4567, CTRL+C to stop
可以看到sinatra的默认端口为4567.
4. 现在可以请求一下看看效果了.
`$> curl "localhost:4567"`
可以看到输出为:
``Hello world, it's 2014-03-31 20:55:23 +0800 at the server!``
5. ok了,你已经有了一个简易的服务器了.
##二.粗略了解sinatra
1. Routing
sinatra的路由配置相当的灵活.首先支持基本的http方法,get,post,put,delete.
$> vim routing.rb
require 'rubygems'
require 'bundler/setup'
require 'sinatra'
get '/get' do "That is a get request method, it's #{Time.now} at the server!" end
post '/post' do "That is a post request method, it's #{Time.now} at the server!" end
put '/put' do "That is a put request method, it's #{Time.now} at the server!" end
delete '/delete' do "That is a delete request method, it's #{Time.now} at the server!" end
一样,启动`ruby routing.rb`.
请求一下吧`curl "localhost:4567/get"`,
输出为`That is a get request method, it's 2014-03-31 21:17:00 +0800 at the server!`
继续请求`curl "localhost:4567/post"`,很好你会看到出错了.
<!DOCTYPE html>
body { text-align:center;font-family:helvetica,arial;font-size:22px; color:#888;margin:20px} #c {margin:0 auto;width:500px;text-align:left}get '/post' do "Hello World" end
这是因为"/post"路径的方法是post
`curl -d "" "localhost:4567/post"`才是正确滴.
上面只是很简单的关于route的例子,当然他也支持RESTful这种东东了.
想了接更多可以参考http://www.sinatrarb.com/intro#Routes
##三:.Filters
sinatra支持两种filter,分别是before和after.顾名思义,befor就是在所有的请求之前执行.after在所有的请求之后执行.
他们都带一个block.
$> vim filter.rb
require 'rubygems'
require 'bundler/setup'
require 'sinatra'
before do @befor = "beeeeeeefor" end
get '/' do "hello, test the #{@befor} filter, it's #{Time.now} at the server!" end
依然是请求一下`curl localhost:4567`
输出为`hello, test the beeeeeeefor filter, it's 2014-03-31 21:39:10 +0800 at the server!`
after类似,就不举例子了.
#####未完待续