学了几天,尝试做一个简单的todo list
先建list.rb
require "haml"
require "sinatra"
require "data_mapper"
DataMapper.setup(:default,"sqlite3://#{Dir.pwd}/test.db")
class List
include DataMapper::Resource
property :id, Serial
property :name, String
property :completed_at, DateTime
end
#index
get '/' do
@lists = List.all
haml :index
end
#edit
get '/list/:id' do
@list = List.get(params[:id])
haml :edit
end
#create
post '/list/create' do
@list = List.create(name: params[:name])
redirect '/'
end
#update
put '/list/:id' do
@list = List.get(params[:id])
@list.name = params[:name]
@list.save
redirect '/'
end
#delete
get '/list/:id/delete' do
@list = List.get(params[:id])
haml :delete
end
delete '/list/:id' do
List.get(params[:id]).destroy
redirect '/'
end
DataMapper.auto_upgrade!
建立config.ru
require "./list"
run Sinatra::Application
建立views文件夹,在views里添加layout.haml,index.haml,edit.haml,delete.haml
layout.haml
!!!
%html
%head
%title TodoList
%body
%h1 To Do List
=yield
index.haml
%form{action:"/list/create",method:"POST"}
%input{type:"text",name:"name",id:"name"}
%input{type:"submit",value:"Add"}
%h1 Lists:
-unless @lists.nil?
%ul
-@lists.each do |list|
%li
%a{href:"/list/#{list.id}"}= list.name
edit.haml
%form{action:"/list/#{@list.id}",method:"POST"}
%input{name:"_method",type:"hidden",value:"put"}
%input{type:"text",name:"name",id:"name",value:"#{@list.name}"}
%input{type:"submit",name:"commit",id:"list_commit",value:"Update"}
%a{href:"/list/#{@list.id}/delete"} Delete
delete.haml
%h2= @list.name
%h3 Are you sure?
%form{action:"/list/#{@list.id}",method:"post"}
%input{type:"hidden",name:"_method",value:"delete"}
%input{type:"submit",value:"Delete"}
or
%a{href:'/'} Cancel
最后运行
ruby list.rb
试试吧
网友评论