Saturday, March 13, 2010

Ruby Rack: Using Objects and defining Middleware

Rack is an interface to many Ruby web application. The last post showed how to use simple lambdas to define applications. Today, we explain how to use classes and what a Rack middleware is.

Rack Applications using Class Objects

Remember from the last post that any Ruby object can be used as a Rack application - as long as it answers to the call method. It’s perfectly valid to use a normal class object. Just take a look at the following code:

class HelloWorld def call(env) return [200, {"Content-Type" => "text/plain"}, body] end end status = lambda do |env| [200, {"Content-Type" => "text/plain"}, ["Running | #{Time.now}"]] end map '/' do run status end map '/hello' do run HelloWorld.new end

Now, whenever we hit the '/hello' URL, the HelloWorld instance's call method is executed. Every Ruby class object can be used in this way inside a Rack application. Just think about all those projects you have made and how easy you can bring them to the web.

Read more at http://blog.sebastianguenther.org/2010/03/13/ruby-rack-using-objects-and-defining-middleware

blog comments powered by Disqus