Usando PATH_INFO y erubis para construir una aplicación (Noah Gibbs)

config.ru

[~/local/src/ruby/sinatra/rack/hangout-framework(master)]$ cat config.ru 
require "erubis"

use Rack::ContentType

def output(text, options = {})
  [ options[:status] || 200,
    {}, [ text ].flatten ]
end

def from_erb(file, vars = {})
  eruby = Erubis::Eruby.new File.read(file)
  output eruby.result vars
end

run proc { |env|
  path = env['PATH_INFO']
  if path =~ %r{^/foo}
    from_erb "template.html.erb"
  else
    output "Not found!", :status => 400
  end
}

Template erb

[~/local/src/ruby/sinatra/rack/hangout-framework(master)]$ cat template.html.erb 
<p> A template! </p>
<% 10.times do -%> <p> Pretty cool! </p> <% end -%>

Arrancando el Servidor

[~/local/src/ruby/sinatra/rack/hangout-framework(master)]$ rackup
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop}

Ejecutando un cliente

[~/local/src/ruby/sinatra/rack/hangout-framework(master)]$ curl -v http://localhost:9292/foochazam
* About to connect() to localhost port 9292 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 9292 (#0)
> GET /foochazam HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8y zlib/1.2.5
> Host: localhost:9292
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: close
< Server: thin 1.5.1 codename Straight Razor
< 
<p> A template! </p>
 <p> Pretty cool! </p>  <p> Pretty cool! </p>  <p> Pretty cool! </p>  
 <p> Pretty cool! </p>  <p> Pretty cool! </p>  <p> Pretty cool! </p>  
 <p> Pretty cool! </p>  <p> Pretty cool! </p>  <p> Pretty cool! </p>  
 <p> Pretty cool! </p> 
* Closing connection #0

Logs del servidor

[~/local/src/ruby/sinatra/rack/hangout-framework(master)]$ rackup
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
 127.0.0.1 - - [20/Oct/2013 12:22:37] "GET /foochazam HTTP/1.1" 200 - 0.0014

Véase

  1. erubis
  2. Noah Gibbs Demo Rack framework for March 6th, 2013 Ruby Hangout.
  3. Ruby Hangout 3-13 Noah Gibbs



Subsecciones
Casiano Rodriguez León 2015-06-18