SlideShare una empresa de Scribd logo
1 de 50
Descargar para leer sin conexión
Haciendo Patria (con Sinatra)
Federico Builes




                                1
2
3
http://www.ruby-lang.org/en/downloads/




                                         4
http://www.mysql.com/downloads/mysql/




                                        5
http://www.sqlite.org/download.html




                                      6
RubyGems
       sinatra
       shotgun
       dm-core
    dm-do-adapter
                     $ gem install [nombre gem]
    dm-migrations
    dm-timestamps
   dm-validations
 dm-sqlite-adapter
(dm-mysql-adapter)
        erubis
        heroku
                                                  7
RubyGems


[sudo] gem install sinatra shotgun dm-core dm-do-adapter dm-migrations dm-timestamps dm-
validations dm-sqlite-adapter erubis heroku --no-ri --no-rdoc




                                                                                           8
Código


   $ git clone git://github.com/febuiles/cp-taller-sample.git



$ wget http://github.com/febuiles/cp-taller-sample/zipball/master




                                                                    9
# garage.rb
require "rubygems"
require "sinatra"

get "/" do
  "Hola"
end


                     10
$ ruby garage.rb
# => localhost:4567

$ shotgun garage.rb
# => localhost:9393



                      11
GET
  POST
   PUT
 DELETE
  HEAD
OPTIONS

          12
get "/items" do
  # ...
end

post "/items" do
  # ...
end

delete "/items" do
  # ...
end
                     13
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    14
# garage.rb

get "/" do
end

get "/items" do
end

get "/items/new" do
end

get "/items/:id" do
end

post "/items" do
end

delete "/items" do
end

put "/items" do
end

                      15
get "/items/:id" do
end

     /items/1
     /items/foo



                      16
Item
-   id            PK
-   title         String
-   author        String
-   description   Text
-   price         String
-   category      String
-   sold          Boolean




                            17
# models.rb
class Item
  include DataMapper::Resource

  property   :id, Serial
  property   :title, String
  property   :author, String
  property   :description, Text
  property   :category, String
  property   :price, String, :default => "20000"
  property   :sold, Boolean, :default => false
end



                                                   18
# models.rb
require 'dm-core'
require 'dm-migrations'
require 'dm-validations'

configure :development do
  DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/data.db")
  # DataMapper::setup(:default, "mysql://user:pwd@localhost/mi_db")
end

class Item
  include DataMapper::Resource

  property   :id, Serial
  property   :title, String
  property   :author, String
  property   :description, Text
  property   :category, String
  property   :price, String, :default => "20000"
  property   :sold, Boolean, :default => false
end

Item.auto_upgrade!

                                                                      19
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    20
# garage.rb
require "sinatra"
require "models"

get "/" do
  redirect "/items"
end

get "/items" do
  @items = Item.all
  erb :index
end

get "/items/new" do
end

get "/items/:id" do
end

post "/items" do
end

delete "/items" do
end
...
                      21
# views/index.erb
<p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p>

<table>
  <tr>
    <th>Producto</th>
    <th>Autor/Fabricante</th>
    <th>Vendido?</th>
    <th>Categoría</th>
  </tr>

  <% @items.each do |item| %>
  <tr>
    <td><a href="/items/<%= item.id %>"><%= item.title %></a></td>
    <td><%= item.author %></td>
    <td><%= item.sold? %></td>
    <td><%= item.category %></td>
  </tr>
  <% end %>
</table>

<p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a
<a href="federico@mheroin.com">federico@mheroin.com</a>.
</p>

<p><br/><a href="/items/new">Agregar Producto</a></p>



                                                                                             22
<a href="/items/<%= item.id %>"><%= item.title %></a>

      <a href="/items/3"><%= item.title %></a>




                                                        23
# models.rb
require 'dm-core'
require 'dm-migrations'
require 'dm-validations'

configure :development do
  DataMapper.auto_upgrade!
  DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/data.db")
end

class Item
  include DataMapper::Resource

  property   :id, Serial
  property   :title, String
  property   :author, String
  property   :description, Text
  property   :category, String
  property   :price, String, :default => "20000"
  property   :sold, Boolean, :default => false

  def sold?
    sold ? "Si" : "No"
  end
end
                                                                24
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    25
# garage.rb
...

get "/items/new" do
  @item = Item.new
  erb :new
end

...

                      26
# /views/new.erb
<h2>Nuevo Producto</h2>

<form method="POST" action="/items">
  <p>
    <label for="title">Titulo:</label>
    <input type="text" name="title" id="title" value="<%= @item.title %>" />
  </p>
  <p>
    <label for="author">Autor/Fabricante:</label>
    <input type="text" name="author" id="fabricante" value="<%= @item.author %>" />
  </p>
  <p>
    <label for="price">Precio ($):</label>
    <input type="text" name="price" id="price" value="<%= @item.price %>"/>
  </p>
  <p>
    <label for="category">Categoría:</label>
    <select name="category">
       <option value="Libro">Libro</option>
       <option value="DVD">DVD</option>
       <option value="Drogas">Drogas</option>
    </select>
  </p>
  <p>
    <label for="description">Descripción:</label>
    <textarea name="description" id="description"><%= @item.description %></textarea>
  </p>
  <p><input type="submit" value="Guardar Producto" /></p>
</form>
                                                                                        27
<form method="POST" action="/items">




                                       28
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    29
# garage.rb

# params => { :title => Algo, :author => "Pepe", :price => "$20000".... }
post "/items" do
  @item = Item.new(params)
  if @item.save
    redirect "/items/#{@item.id}"    # => /items/1
  else
    erb :new
  end
end




                                                                            30
# garage.rb

# params => { :title => Algo, :author => "Pepe", :price => "$20000".... }
post "/items" do
  @item = Item.new(params)
  if @item.save
    redirect "/items/#{@item.id}"    # => /items/1
  else
    erb :new
  end
end




                                                                            31
# models.rb
# -*- coding: utf-8 -*-

class Item
  include DataMapper::Resource

  property :id, Serial

  property   :title, String
  property   :author, String
  property   :description, Text
  property   :price, String, :default => "20000"
  property   :category, String
  property   :sold, Boolean, :default => false

  validates_presence_of :title, :message => "El producto necesita un título"
  validates_presence_of :author, :message => "El producto necesita un autor ó fabricante"
  validates_presence_of :price, :message => "El precio del producto no puede estar vacío"

  def sold?
    sold ? "Si" : "No"
  end
end




                                                                                            32
# /views/new.erb
<h2>Nuevo Producto</h2>
<% if @item.errors %>
  <ul class="warning">
    <% @item.errors.each do |error| %>
    <li><%= error %></li>
    <% end %>
  </ul>
<% end %>
<form method="POST" action="/items">



                                         33
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    34
# garage.rb

get "/items/:id" do
  @item = Item.get(params[:id])
  erb :show
end



                                  35
# views/show.erb
<h2><%= @item.title %></h2>
<h3><%= @item.category %></h3>
<p><%= @item.description %>
  <em>$<%= @item.price %></em>
</p>

<p>
  <%= buy_item_link(@item) %>
  <%= delete_item_link(@item) %>
</p>
                                   36
37
<form action="/items" method="post">
  <input type="hidden" name="_method" value="put" />
  <input type="hidden" name="id" value="7" />
  <input type="submit" value="Comprar" />
</form>

<form action="/items" method="post">
  <input type="hidden" name="_method" value="delete" />
  <input type="hidden" name="id" value="7" />
  <input type="submit" value="Eliminar" />
</form>




                                                          38
# garage.rb
helpers do

  def buy_item_link(item)
     html = <<HTML
<form action="/items" method="post">
  <input type="hidden" name="_method" value="put" />
  <input type="hidden" name="id" value="#{item.id}" />
  <input type="submit" value="Comprar" />
</form>
HTML
     html if !item.nil?
  end

  def delete_item_link(item)
     html = <<HTML
<form action="/items" method="post">
  <input type="hidden" name="_method" value="delete" />
  <input type="hidden" name="id" value="#{item.id}" />
  <input type="submit" value="Eliminar" />
</form>
HTML
     html if !item.nil?
  end
end
                                                          39
<h2><%= @item.title %></h2>
<h3><%= @item.category %></h3>
<p><%= @item.description %>
  <em>$<%= @item.price %></em>
</p>

<p>
  <%= buy_item_link(@item) %>
  <%= delete_item_link(@item) %>
</p>
                                   40
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    41
# garage.rb
delete "/items" do
  item = Item.get(params[:id])
  item.destroy unless item.nil?

  redirect "/items"
end


                                  42
# views/index.erb
<p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p>

<table>
  <tr>
    <th>Producto</th>
    <th>Autor/Fabricante</th>
    <th>Vendido?</th>
    <th>Categoría</th>
  </tr>

  <% @items.each do |item| %>
  <tr>
    <td><a href="/items/<%= item.id %>"><%= item.title %></a></td>
    <td><%= item.author %></td>
    <td><%= item.sold? %></td>
    <td><%= item.category %></td>
    <td><%= buy_item_link(item) unless item.sold %></td>
  </tr>
  <% end %>
</table>

<p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a
<a href="federico@mheroin.com">federico@mheroin.com</a>.
</p>



                                                                                             43
GET      /items       -   Lista de todos los items
GET      /items/new   -   Vista para crear nuevo item
GET      /items/:id   -   Vista item específico
POST     /items       -   Crea un item nuevo
DELETE   /items       -   Elimina un item
PUT      /items       -   Compra un item




                                                    44
# garage.rb
put "/items" do
  item = Item.get(params[:id])
  error 500 if item.nil?

  if item.sell
    @items = Item.all
    @notice = "Felicitaciones por la compra de: #{item.title}"
    erb :index
  else
    not_found("No encontramos el producto que intentas comprar")
  end
end




                                                                   45
# models.rb

class Item
  include DataMapper::Resource

  property :id, Serial

  property   :title, String
  property   :author, String
  property   :description, Text
  property   :price, String, :default => "20000"
  property   :category, String
  property   :sold, Boolean, :default => false

  validates_presence_of :title, :message => "El producto necesita un título"
  validates_presence_of :author, :message => "El producto necesita un autor ó fabricante"
  validates_presence_of :price, :message => "El precio del producto no puede estar vacío"

  def sold?
    sold ? "Si" : "No"
  end

  def sell
    self.sold = true
    save
  end
end


                                                                                            46
# garage.rb
put "/items" do
  item = Item.get(params[:id])
  error 500 if item.nil?

  if item.sell
    @items = Item.all
    @notice = "Felicitaciones por la compra de: #{item.title}"
    erb :index
  else
    not_found("No encontramos el producto que intentas comprar")
  end
end




                                                                   47
# views/index.erb
<p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p>

<% if @notice %>
  <span class="notice"><%= @notice %></span>
<% end %>

<table>
  <tr>
    <th>Producto</th>
    <th>Autor/Fabricante</th>
    <th>Vendido?</th>
    <th>Categoría</th>
  </tr>

  <% @items.each do |item| %>
  <tr>
    <td><a href="/items/<%= item.id %>"><%= item.title %></a></td>
    <td><%= item.author %></td>
    <td><%= item.sold? %></td>
    <td><%= item.category %></td>
    <td><%= buy_item_link(item) unless item.sold %></td>
  </tr>
  <% end %>
</table>

<p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a
<a href="federico@mheroin.com">federico@mheroin.com</a>.
</p>

                                                                                             48
# garage.rb
require "sinatra"
require "models"

before do
  content_type :html, :charset => 'utf-8'
end

get "/" do
  redirect "/items"
end

                                            49
<!-- views/layout.erb -->
<html>
  <head>
    <link rel="stylesheet" href="/screen.css" type="text/css"
media="screen" />
    <title>Venta de Garage</title>
  </head>

  <body>
    <h1>Venta de Garage</h1>
    <%= yield %>
  </body>
</html>




                                                                50

Más contenido relacionado

La actualidad más candente

Desarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryDesarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryJavier P.
 
Silex, desarrollo web ágil y profesional con PHP
Silex, desarrollo web ágil y profesional con PHPSilex, desarrollo web ágil y profesional con PHP
Silex, desarrollo web ágil y profesional con PHPJavier Eguiluz
 
Desarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryDesarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryJavier P.
 
Noticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de NoticiasNoticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de Noticiasroundcomedian383
 
Wp config.php
Wp config.phpWp config.php
Wp config.phpgregozz
 
Symfony parte 14 Consultas SQL - Páginador
Symfony parte 14 Consultas SQL - PáginadorSymfony parte 14 Consultas SQL - Páginador
Symfony parte 14 Consultas SQL - PáginadorRodrigo Miranda
 
Drupal7 para desarrolladores
Drupal7 para desarrolladoresDrupal7 para desarrolladores
Drupal7 para desarrolladoresPedro Cambra
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a DjangoJoaquim Rocha
 
Informe grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuencaInforme grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuencapaulcuenca9
 
Julissarodriguezvilca
JulissarodriguezvilcaJulissarodriguezvilca
JulissarodriguezvilcajulissaJRV
 
Programa que almacena en una base de datos las características de un carro co...
Programa que almacena en una base de datos las características de un carro co...Programa que almacena en una base de datos las características de un carro co...
Programa que almacena en una base de datos las características de un carro co...jbersosa
 
Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Aida Albarrán
 
Ejemplo de formulario
Ejemplo de formularioEjemplo de formulario
Ejemplo de formularioOVAWEB
 

La actualidad más candente (20)

Php2
Php2 Php2
Php2
 
Desarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryDesarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQuery
 
Silex, desarrollo web ágil y profesional con PHP
Silex, desarrollo web ágil y profesional con PHPSilex, desarrollo web ágil y profesional con PHP
Silex, desarrollo web ágil y profesional con PHP
 
Desarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQueryDesarrollo de aplicaciones web usando Catalyst y jQuery
Desarrollo de aplicaciones web usando Catalyst y jQuery
 
Noticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de NoticiasNoticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de Noticias
 
Introducción a Flask
Introducción a FlaskIntroducción a Flask
Introducción a Flask
 
Wp config.php
Wp config.phpWp config.php
Wp config.php
 
Symfony parte 14 Consultas SQL - Páginador
Symfony parte 14 Consultas SQL - PáginadorSymfony parte 14 Consultas SQL - Páginador
Symfony parte 14 Consultas SQL - Páginador
 
Introducción a DJango
Introducción a DJangoIntroducción a DJango
Introducción a DJango
 
Angularjs Lógica de negocio
Angularjs Lógica de negocioAngularjs Lógica de negocio
Angularjs Lógica de negocio
 
Drupal7 para desarrolladores
Drupal7 para desarrolladoresDrupal7 para desarrolladores
Drupal7 para desarrolladores
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a Django
 
Php
PhpPhp
Php
 
Informe grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuencaInforme grupal f_arinango_ cuenca
Informe grupal f_arinango_ cuenca
 
Jquery
JqueryJquery
Jquery
 
Novedades de aries
Novedades de ariesNovedades de aries
Novedades de aries
 
Julissarodriguezvilca
JulissarodriguezvilcaJulissarodriguezvilca
Julissarodriguezvilca
 
Programa que almacena en una base de datos las características de un carro co...
Programa que almacena en una base de datos las características de un carro co...Programa que almacena en una base de datos las características de un carro co...
Programa que almacena en una base de datos las características de un carro co...
 
Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020
 
Ejemplo de formulario
Ejemplo de formularioEjemplo de formulario
Ejemplo de formulario
 

Destacado

Coffeescript en cinco (o diez) minutos
Coffeescript en cinco (o diez) minutosCoffeescript en cinco (o diez) minutos
Coffeescript en cinco (o diez) minutosfebuiles
 
Business Drivers State Agencies
Business Drivers State AgenciesBusiness Drivers State Agencies
Business Drivers State AgenciesRichard Sutton
 
Mi Primera Vez
Mi Primera VezMi Primera Vez
Mi Primera Vezfebuiles
 
Your guide to online advertising
Your guide to online advertisingYour guide to online advertising
Your guide to online advertisingDavid Bellerive
 
Marc De Bel Stien
Marc De Bel StienMarc De Bel Stien
Marc De Bel StienMegamindy
 
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de Programación
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de ProgramaciónTrabajo práctico sobre Clojure, Evaluación de un Lenguaje de Programación
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de ProgramaciónEmmanuel Fontán
 

Destacado (9)

Coffeescript en cinco (o diez) minutos
Coffeescript en cinco (o diez) minutosCoffeescript en cinco (o diez) minutos
Coffeescript en cinco (o diez) minutos
 
ACL2009
ACL2009ACL2009
ACL2009
 
Business Drivers State Agencies
Business Drivers State AgenciesBusiness Drivers State Agencies
Business Drivers State Agencies
 
ACL2008
ACL2008ACL2008
ACL2008
 
Mi Primera Vez
Mi Primera VezMi Primera Vez
Mi Primera Vez
 
Your guide to online advertising
Your guide to online advertisingYour guide to online advertising
Your guide to online advertising
 
Sarah
SarahSarah
Sarah
 
Marc De Bel Stien
Marc De Bel StienMarc De Bel Stien
Marc De Bel Stien
 
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de Programación
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de ProgramaciónTrabajo práctico sobre Clojure, Evaluación de un Lenguaje de Programación
Trabajo práctico sobre Clojure, Evaluación de un Lenguaje de Programación
 

Similar a Haciendo Patria con Sinatra

Desarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQueryDesarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQueryJavier P.
 
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos Aires
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos AiresPresentación Ruby on Rails en Softare Freedom Day 09 Buenos Aires
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos Airespeterpunk
 
M. carrito d compra en phpfinal
M. carrito d compra en phpfinalM. carrito d compra en phpfinal
M. carrito d compra en phpfinalAbyliel Garcia
 
Dom html - java script
Dom   html - java scriptDom   html - java script
Dom html - java scriptDaniel Grippo
 
Javascript en proyectos reales: jQuery
Javascript en proyectos reales: jQueryJavascript en proyectos reales: jQuery
Javascript en proyectos reales: jQueryDavid Arango
 
Un newbie conoce a Sinatra
Un newbie conoce a SinatraUn newbie conoce a Sinatra
Un newbie conoce a SinatraJano González
 
Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Javier Eguiluz
 
Intro aplicaciones web con php
Intro aplicaciones web con phpIntro aplicaciones web con php
Intro aplicaciones web con phpFer Nando
 
Acceptance testing with Steak and Capybara
Acceptance testing with Steak and CapybaraAcceptance testing with Steak and Capybara
Acceptance testing with Steak and CapybaraSergio Gil
 
Noticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de NoticiasNoticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de Noticiascameronvoeflvlxeo
 
Pagina web en css
Pagina web en cssPagina web en css
Pagina web en cssnelson4409
 

Similar a Haciendo Patria con Sinatra (20)

Desarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQueryDesarrollando aplicaciones web usando Catalyst y jQuery
Desarrollando aplicaciones web usando Catalyst y jQuery
 
Jquery
JqueryJquery
Jquery
 
Php
PhpPhp
Php
 
Python scraping
Python scrapingPython scraping
Python scraping
 
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos Aires
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos AiresPresentación Ruby on Rails en Softare Freedom Day 09 Buenos Aires
Presentación Ruby on Rails en Softare Freedom Day 09 Buenos Aires
 
Doctrine2 sf2Vigo
Doctrine2 sf2VigoDoctrine2 sf2Vigo
Doctrine2 sf2Vigo
 
M. carrito d compra en phpfinal
M. carrito d compra en phpfinalM. carrito d compra en phpfinal
M. carrito d compra en phpfinal
 
Dom html - java script
Dom   html - java scriptDom   html - java script
Dom html - java script
 
Javascript en proyectos reales: jQuery
Javascript en proyectos reales: jQueryJavascript en proyectos reales: jQuery
Javascript en proyectos reales: jQuery
 
Un newbie conoce a Sinatra
Un newbie conoce a SinatraUn newbie conoce a Sinatra
Un newbie conoce a Sinatra
 
En 20 minutos ... jQuery
En 20 minutos ... jQueryEn 20 minutos ... jQuery
En 20 minutos ... jQuery
 
Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)
 
Intro aplicaciones web con php
Intro aplicaciones web con phpIntro aplicaciones web con php
Intro aplicaciones web con php
 
Acceptance testing with Steak and Capybara
Acceptance testing with Steak and CapybaraAcceptance testing with Steak and Capybara
Acceptance testing with Steak and Capybara
 
Jquery para principianes
Jquery para principianesJquery para principianes
Jquery para principianes
 
J M E R L I N P H P
J M E R L I N P H PJ M E R L I N P H P
J M E R L I N P H P
 
Noticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de NoticiasNoticias de negocios, Finanzas Personales y Dinero de Noticias
Noticias de negocios, Finanzas Personales y Dinero de Noticias
 
Código Bonito con PHP
Código Bonito con PHPCódigo Bonito con PHP
Código Bonito con PHP
 
Pagina web en css
Pagina web en cssPagina web en css
Pagina web en css
 
Varios codigos sql
Varios codigos sqlVarios codigos sql
Varios codigos sql
 

Último

International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)GDGSucre
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan JosephBRAYANJOSEPHPEREZGOM
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx241521559
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíassuserf18419
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITMaricarmen Sánchez Ruiz
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxLolaBunny11
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricKeyla Dolores Méndez
 
Desarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfDesarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfJulian Lamprea
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...silviayucra2
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveFagnerLisboa3
 

Último (10)

International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Joseph
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnología
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptx
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
 
Desarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfDesarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdf
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial Uninove
 

Haciendo Patria con Sinatra

  • 1. Haciendo Patria (con Sinatra) Federico Builes 1
  • 2. 2
  • 3. 3
  • 7. RubyGems sinatra shotgun dm-core dm-do-adapter $ gem install [nombre gem] dm-migrations dm-timestamps dm-validations dm-sqlite-adapter (dm-mysql-adapter) erubis heroku 7
  • 8. RubyGems [sudo] gem install sinatra shotgun dm-core dm-do-adapter dm-migrations dm-timestamps dm- validations dm-sqlite-adapter erubis heroku --no-ri --no-rdoc 8
  • 9. Código $ git clone git://github.com/febuiles/cp-taller-sample.git $ wget http://github.com/febuiles/cp-taller-sample/zipball/master 9
  • 10. # garage.rb require "rubygems" require "sinatra" get "/" do "Hola" end 10
  • 11. $ ruby garage.rb # => localhost:4567 $ shotgun garage.rb # => localhost:9393 11
  • 12. GET POST PUT DELETE HEAD OPTIONS 12
  • 13. get "/items" do # ... end post "/items" do # ... end delete "/items" do # ... end 13
  • 14. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 14
  • 15. # garage.rb get "/" do end get "/items" do end get "/items/new" do end get "/items/:id" do end post "/items" do end delete "/items" do end put "/items" do end 15
  • 16. get "/items/:id" do end /items/1 /items/foo 16
  • 17. Item - id PK - title String - author String - description Text - price String - category String - sold Boolean 17
  • 18. # models.rb class Item include DataMapper::Resource property :id, Serial property :title, String property :author, String property :description, Text property :category, String property :price, String, :default => "20000" property :sold, Boolean, :default => false end 18
  • 19. # models.rb require 'dm-core' require 'dm-migrations' require 'dm-validations' configure :development do DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/data.db") # DataMapper::setup(:default, "mysql://user:pwd@localhost/mi_db") end class Item include DataMapper::Resource property :id, Serial property :title, String property :author, String property :description, Text property :category, String property :price, String, :default => "20000" property :sold, Boolean, :default => false end Item.auto_upgrade! 19
  • 20. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 20
  • 21. # garage.rb require "sinatra" require "models" get "/" do redirect "/items" end get "/items" do @items = Item.all erb :index end get "/items/new" do end get "/items/:id" do end post "/items" do end delete "/items" do end ... 21
  • 22. # views/index.erb <p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p> <table> <tr> <th>Producto</th> <th>Autor/Fabricante</th> <th>Vendido?</th> <th>Categoría</th> </tr> <% @items.each do |item| %> <tr> <td><a href="/items/<%= item.id %>"><%= item.title %></a></td> <td><%= item.author %></td> <td><%= item.sold? %></td> <td><%= item.category %></td> </tr> <% end %> </table> <p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a <a href="federico@mheroin.com">federico@mheroin.com</a>. </p> <p><br/><a href="/items/new">Agregar Producto</a></p> 22
  • 23. <a href="/items/<%= item.id %>"><%= item.title %></a> <a href="/items/3"><%= item.title %></a> 23
  • 24. # models.rb require 'dm-core' require 'dm-migrations' require 'dm-validations' configure :development do DataMapper.auto_upgrade! DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/data.db") end class Item include DataMapper::Resource property :id, Serial property :title, String property :author, String property :description, Text property :category, String property :price, String, :default => "20000" property :sold, Boolean, :default => false def sold? sold ? "Si" : "No" end end 24
  • 25. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 25
  • 26. # garage.rb ... get "/items/new" do @item = Item.new erb :new end ... 26
  • 27. # /views/new.erb <h2>Nuevo Producto</h2> <form method="POST" action="/items"> <p> <label for="title">Titulo:</label> <input type="text" name="title" id="title" value="<%= @item.title %>" /> </p> <p> <label for="author">Autor/Fabricante:</label> <input type="text" name="author" id="fabricante" value="<%= @item.author %>" /> </p> <p> <label for="price">Precio ($):</label> <input type="text" name="price" id="price" value="<%= @item.price %>"/> </p> <p> <label for="category">Categoría:</label> <select name="category"> <option value="Libro">Libro</option> <option value="DVD">DVD</option> <option value="Drogas">Drogas</option> </select> </p> <p> <label for="description">Descripción:</label> <textarea name="description" id="description"><%= @item.description %></textarea> </p> <p><input type="submit" value="Guardar Producto" /></p> </form> 27
  • 29. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 29
  • 30. # garage.rb # params => { :title => Algo, :author => "Pepe", :price => "$20000".... } post "/items" do @item = Item.new(params) if @item.save redirect "/items/#{@item.id}" # => /items/1 else erb :new end end 30
  • 31. # garage.rb # params => { :title => Algo, :author => "Pepe", :price => "$20000".... } post "/items" do @item = Item.new(params) if @item.save redirect "/items/#{@item.id}" # => /items/1 else erb :new end end 31
  • 32. # models.rb # -*- coding: utf-8 -*- class Item include DataMapper::Resource property :id, Serial property :title, String property :author, String property :description, Text property :price, String, :default => "20000" property :category, String property :sold, Boolean, :default => false validates_presence_of :title, :message => "El producto necesita un título" validates_presence_of :author, :message => "El producto necesita un autor ó fabricante" validates_presence_of :price, :message => "El precio del producto no puede estar vacío" def sold? sold ? "Si" : "No" end end 32
  • 33. # /views/new.erb <h2>Nuevo Producto</h2> <% if @item.errors %> <ul class="warning"> <% @item.errors.each do |error| %> <li><%= error %></li> <% end %> </ul> <% end %> <form method="POST" action="/items"> 33
  • 34. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 34
  • 35. # garage.rb get "/items/:id" do @item = Item.get(params[:id]) erb :show end 35
  • 36. # views/show.erb <h2><%= @item.title %></h2> <h3><%= @item.category %></h3> <p><%= @item.description %> <em>$<%= @item.price %></em> </p> <p> <%= buy_item_link(@item) %> <%= delete_item_link(@item) %> </p> 36
  • 37. 37
  • 38. <form action="/items" method="post"> <input type="hidden" name="_method" value="put" /> <input type="hidden" name="id" value="7" /> <input type="submit" value="Comprar" /> </form> <form action="/items" method="post"> <input type="hidden" name="_method" value="delete" /> <input type="hidden" name="id" value="7" /> <input type="submit" value="Eliminar" /> </form> 38
  • 39. # garage.rb helpers do def buy_item_link(item) html = <<HTML <form action="/items" method="post"> <input type="hidden" name="_method" value="put" /> <input type="hidden" name="id" value="#{item.id}" /> <input type="submit" value="Comprar" /> </form> HTML html if !item.nil? end def delete_item_link(item) html = <<HTML <form action="/items" method="post"> <input type="hidden" name="_method" value="delete" /> <input type="hidden" name="id" value="#{item.id}" /> <input type="submit" value="Eliminar" /> </form> HTML html if !item.nil? end end 39
  • 40. <h2><%= @item.title %></h2> <h3><%= @item.category %></h3> <p><%= @item.description %> <em>$<%= @item.price %></em> </p> <p> <%= buy_item_link(@item) %> <%= delete_item_link(@item) %> </p> 40
  • 41. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 41
  • 42. # garage.rb delete "/items" do item = Item.get(params[:id]) item.destroy unless item.nil? redirect "/items" end 42
  • 43. # views/index.erb <p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p> <table> <tr> <th>Producto</th> <th>Autor/Fabricante</th> <th>Vendido?</th> <th>Categoría</th> </tr> <% @items.each do |item| %> <tr> <td><a href="/items/<%= item.id %>"><%= item.title %></a></td> <td><%= item.author %></td> <td><%= item.sold? %></td> <td><%= item.category %></td> <td><%= buy_item_link(item) unless item.sold %></td> </tr> <% end %> </table> <p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a <a href="federico@mheroin.com">federico@mheroin.com</a>. </p> 43
  • 44. GET /items - Lista de todos los items GET /items/new - Vista para crear nuevo item GET /items/:id - Vista item específico POST /items - Crea un item nuevo DELETE /items - Elimina un item PUT /items - Compra un item 44
  • 45. # garage.rb put "/items" do item = Item.get(params[:id]) error 500 if item.nil? if item.sell @items = Item.all @notice = "Felicitaciones por la compra de: #{item.title}" erb :index else not_found("No encontramos el producto que intentas comprar") end end 45
  • 46. # models.rb class Item include DataMapper::Resource property :id, Serial property :title, String property :author, String property :description, Text property :price, String, :default => "20000" property :category, String property :sold, Boolean, :default => false validates_presence_of :title, :message => "El producto necesita un título" validates_presence_of :author, :message => "El producto necesita un autor ó fabricante" validates_presence_of :price, :message => "El precio del producto no puede estar vacío" def sold? sold ? "Si" : "No" end def sell self.sold = true save end end 46
  • 47. # garage.rb put "/items" do item = Item.get(params[:id]) error 500 if item.nil? if item.sell @items = Item.all @notice = "Felicitaciones por la compra de: #{item.title}" erb :index else not_found("No encontramos el producto que intentas comprar") end end 47
  • 48. # views/index.erb <p>Esta es mi venta de garage, hay muchas como ella pero esta es la mía.</p> <% if @notice %> <span class="notice"><%= @notice %></span> <% end %> <table> <tr> <th>Producto</th> <th>Autor/Fabricante</th> <th>Vendido?</th> <th>Categoría</th> </tr> <% @items.each do |item| %> <tr> <td><a href="/items/<%= item.id %>"><%= item.title %></a></td> <td><%= item.author %></td> <td><%= item.sold? %></td> <td><%= item.category %></td> <td><%= buy_item_link(item) unless item.sold %></td> </tr> <% end %> </table> <p>Pregunte por lo que no vea. Si está interesado en mi cuerpo también me puede escribir a <a href="federico@mheroin.com">federico@mheroin.com</a>. </p> 48
  • 49. # garage.rb require "sinatra" require "models" before do content_type :html, :charset => 'utf-8' end get "/" do redirect "/items" end 49
  • 50. <!-- views/layout.erb --> <html> <head> <link rel="stylesheet" href="/screen.css" type="text/css" media="screen" /> <title>Venta de Garage</title> </head> <body> <h1>Venta de Garage</h1> <%= yield %> </body> </html> 50