1. Install sinatra gem
gem install sinatra --no-ri --no-rdoc
2. Basic App
#!/usr/bin/ruby
require 'sinatra'
get '/' do"Just Do It"
end
ruby低于1.9,需要在文件开头加require 'rubygems'
ruby basic.rb
Open up your browser and go to http://localhost:4567.
3. Inline Template
Slim is a fantastic template engine that makes this a much easier task.
Install slime: $ gem install slime
#!/usr/bin/ruby
require "sinatra"
require 'slim'get '/' doslim:index
end#Inline templates always come after the __END__ declaration, and each template begins with @@.__END__@@layout
doctype html
htmlheadmeta charset="utf-8"title Just Do itlink rel="stylesheet" media="screen,projection" href="/style.css"/[if lt IE 9]script scr="http://html5shiv.googlecode.com/svn/trunk/html5.js"bodyh1 Just Doi it== yield @@index
h2 My tasks
ul.tasksli Get Milk
"@@layout" template: This will automatically be rendered with every view and provides a basic HTML5 scaffolding. The key line in the layout template is right at the end (==yield
). The yield
statement renders the content from the whichever template was requested by the handler (in this case, ‘index’).
4. Extend Views (把视图分离出来)
5. Dynamic Content
在主文件rb中增加代码
get "/:task" do@task=params[:task].split('-').join(' ').capitalizeslim :task
end
让‘@task’ equal to the value of params[:task]
对应的视图文件task.slim
h2 My Tasks
= @task
其中@task匹配对应的URL。
6.Forms(窗体处理)
本例把index.slim的内容替换成
form action="/" method="POST"input type="text" name="task"input.button type="submit" value="New Task >>"
这样会在“/”页面显示一个窗体(一个文本框、一个提交按钮)
提交的内容需要一个handler来处理,再sinatra文件中用post(对应窗体提交method),代码如下:
post '/' do@task = params[:task]slim :task
end