Rack

Base de todo ruby web framework

Rails es una rack application..

Por que?

Que hace?

  • Envuelve el request y el response
  • Provee una interfaz comĂșn para aplicaciones web
  • Permite que varias aplicaciones se encadenen juntas(Middleware).

Applicacion Rack

  • Clase ruby con un metodo "call"
  • Acepta un parametro(env) con informacion sobre el request.
  • Devuelve un array:

[status_code, {headers}, [body]]

require "rack"
require "thin"

class HelloWorld
  def call(env)
    [ 200, { "Content-Type" => "text/plain" }, ["Hello World"] ]
  end
end

Rack::Handler::Thin.run HelloWorld.new

Lambda

require "rack"
require "thin"

app = -> (env) do
  [ 200, { "Content-Type" => "text/plain" }, env ]
end

Rack::Handler::Thin.run app

Rack Application server

  • Una clase dentro del modulo Rack::Handler
  • Tiene un metodo run al que se le pasa una applicacion rack.
  • Llama el metodo "call" de la aplicacion y le pasa el parametro env.
require 'rack'

@app = MyApp.new

Rack::Handler::Puma.run(@app)

Text

Text

Middleware

Requerimientos

  • los mismos que una applicacion rack.
  • Initialize que acepta un objeto app
  • Normalmente llama a app.call
require "rack"
require "thin"

app = -> (env) do
  sleep 3
  [ 200, { "Content-Type" => "text/plain" }, ["Hello World\n"] ]
end

class LoggingMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    before = Time.now.to_i
    status, headers, body = @app.call(env)
    after = Time.now.to_i
    log_message = "App took #{after - before} seconds."

    [status, headers, body << log_message]
  end
end

Rack::Handler::Thin.run LoggingMiddleware.new(app)

Rack::Builder

app =
Rack::Builder.new do |builder|
  builder.use FilterLocalHost
  builder.run RackApp.new
end

Rack::Handler::Thin app

Demo...

Middlewares out of the box

  • Rack::URLMap, to route to multiple applications inside the same process.

  • Rack::CommonLogger, for creating Apache-style logfiles.

  • Rack::ShowException, for catching unhandled exceptions and presenting them in a nice and helpful way with clickable backtrace.

  • Rack::File, for serving static files.

Made with Slides.com