Arquivo

Arquivo da Categoria ‘Rack’

Creating custom middlewares with Rack

12, dezembro, 2011 Sem comentários

To kick off, What is Rack?

A Rack applications is a object that has a methods named ‘call’ and that method receive the enviroment as a argument and return a array with exactly three values: status, header and body.

The following is a simple example:


class App
  def call(env)
    [200, {"Content-Type" => "text/plain"},["LucasAllan.com"]]
  end
end

Rack is the base of a lot of web frameworks written in Ruby, like Ruby On Rails, Sinatra, Camping and others…

What is a Rack Middleware?

Rack middleware is a kind of filter to requests in a Rack application. It behaves like a rack application and needs the same things that a simple rack application. It’s like a rack application inside another rack application.

I created a file named cache_control.rb with the follow code:

require 'rack/utils'

module Rack

  class CacheControl
    include Rack::Utils

    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, body = @app.call(env)
      headers = Utils::HeaderHash.new(headers)
      headers['Cache-Control'] = "no-cache"
      [status, headers, body]
    end
  end
end

In that code, I get the enviroment (with headers, content and http code) and I can manipulate it. In that case I just added a new header.

Now in my Rack Application I will load that middleware and use it.

require 'rack'
require 'cache_control'

class App
  def call(env)
    [200, {"Content-Type" => "text/plain"},["LucasAllan.com"]]
  end
end

use Rack::CacheControl
run MyApp.new

I used the word ‘use’ to call my middleware.

You can run this app using the Thin server, for this you must have the Thin installed: gem install thin

And use the follow command:
You the file name of your application is config.ru (Rack standard), use it:

thin -R config.ru start

If don’t, replace config.ru for the right filename.

You can try to access the application using your browser or curl:

curl -i localhost:3000

HTTP/1.1 200 OK
Content-Type: text/plain
Cache-Control: no-cache
Connection: close
Server: thin 1.3.1 codename Triple Espresso

LucasAllan.com

Categories: Rack, Ruby Tags: ,