Skip to content

Instantly share code, notes, and snippets.

@oinak
Created May 7, 2013 16:46
Show Gist options
  • Save oinak/5534133 to your computer and use it in GitHub Desktop.
Save oinak/5534133 to your computer and use it in GitHub Desktop.
Curso de Introducción a Ruby on Rails - Ejercicio 2
source 'https://rubygems.org'
gem "sinatra", "~> 1.4.2"
gem "data_mapper", "~> 1.2.0"
gem "dm-sqlite-adapter", "~> 1.2.0"
gem "haml", "~> 4.0.1"
require 'sinatra'
require 'data_mapper'
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")
# Models
class Task
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :completed_at, DateTime
end
# Routes/controller
get '/' do
@tasks = Task.all
haml :index, :format => :html5
end
post '/' do
Task.create(:name => params[:name])
redirect '/'
end
get '/:id' do
@task = Task.get(params[:id])
haml :edit, :format => :html5
end
put '/:id' do
task = Task.get(params[:id])
task.completed_at = params[:completed] ? Time.now : nil
task.name = (params[:name])
task.save ? (redirect '/') : (redirect '/' + task.id.to_s)
end
delete '/:id' do
Task.get(params[:id]).destroy
redirect '/'
end
DataMapper.auto_upgrade!
# Inline views
__END__
@@ layout
!!! 5
%html
%head
%meta(charset="utf-8")
%title To Do List
%style li.completed{text-decoration:line-through;}
%body
%h1 <a title="Show Tasks" href="/">To Do List</a>
= yield
@@ index
%form(action="/" method="POST")
%input#name(type="text" name="name")
%input(type="submit" value="Add Task!")
%ul#tasks
-@tasks.each do |task|
%li{:class => (task.completed_at ? "completed": nil)}
%a(href="/#{task.id}")= task.name
@@ edit
%form(action="#{@task.id}" method="POST")
%input(name="_method" type="hidden" value="PUT")
%input#name(type="text" name="name"value="#{@task.name}")
%input#completed{:name => "completed",:type => "checkbox",:value => "done",:checked => (@task.completed_at ? "checked": nil)}
%input(name="commit" type="submit" value="Update")
%form(action="#{@task.id}" method="POST")
%input(name="_method" type="hidden" value="DELETE")
%input(type="submit" value="Delete") or <a href="/">Cancel</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment