Chinaunix首页 | 论坛 | 博客
  • 博客访问: 395622
  • 博文数量: 69
  • 博客积分: 1984
  • 博客等级: 上尉
  • 技术积分: 953
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-28 00:43
个人简介

学无所长,一事无成

文章分类

全部博文(69)

文章存档

2015年(19)

2014年(14)

2013年(9)

2012年(17)

2010年(10)

我的朋友

分类: Python/Ruby

2014-04-22 15:34:11



一、安装
gem install sinatra
gem install thin rerun

sinatra 支持多种模板,建议选择内建的 erb 或安装 haml
gem install haml

二、Hello World 程序

  1. require 'sinatra'

  2. set :bind => '0.0.0.0' # 绑定到所有ip 地址

  3. get '/' do
  4.   "Hello world, it's #{Time.now} at the server!"
  5. end
运行: ruby hello_world.rb 
浏览器就可以访问:

三、一些基础知识

路由 Routing
四种基本的 http 访问请求
  • GET
  • POST
  • PUT
  • DELETE
  1. get '/dogs' do
  2.   # get a listing of all the dogs
  3. end

  4. get '/dog/:id' do
  5.   # just get one dog, you might find him like this:
  6.   @dog = Dog.find(params[:id])
  7.   # using the params convention, you specified in your route
  8. end

  9. post '/dog' do
  10.   # create a new dog listing
  11. end

  12. put '/dog/:id' do
  13.   # HTTP PUT request method to update an existing dog
  14. end

  15. delete '/dog/:id' do
  16.   # 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.

  1. before do
  2.   MyStore.connect unless MyStore.connected?
  3. end

  4. get '/' do
  5.   @list = MyStore.find(:all)
  6.   erb :index
  7. end

after

The after method lets you pass a block to be evaluated after each and every route gets processed.

  1. after do
  2.   MyStore.disconnect
  3. 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.

  1. before '/admin/*' do
  2.   
  3. end

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:


  1. get '/' do
  2.   redirect '/someplace/else'
  3. 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:


  1. enable :sessions

Then you will be able to use the default cookie based session handler in your application:

  1. get '/' do
  2.   session['counter'] ||= 0
  3.   session['counter'] += 1
  4.   "You've hit this page #{session['counter']} times!"
  5. end







阅读(1033) | 评论(0) | 转发(0) |
0

上一篇:Sinatra 学习

下一篇:Dojo学习-1:Hello Dojo!

给主人留下些什么吧!~~