Thursday, 29 December 2011

Create a basic Ruby app with Rack middleware - part 1

This post - or may be a series of posts - on Rack is intended to understand how modern Ruby frameworks work. Frameworks such as Sinatra or Ruby on Rails use Rack middleware to exchange requests and responses to application servers. Old time of CGI or FCGI are gone. The code below shows how simple is to start a ruby server to serve a 404 error page:

app = lambda do |env|
body = File.open(File.dirname(__FILE__)+'/404.html', 'r').read
[404, {'Content-Type' => 'text/html'}, [body]]
end

run app


Save the previous script in a file named config.ru. If you have a page 404.html in the same directory of config.ru and you run:

> rackup -p 3000

You will get the 404.html page by connecting to http://localhost:3000. Please notice the curly braces between body: it is needed by Ruby 1.9. The run app statement run the lambda we just created.

1 comments:

  1. Hello, I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wish you best of luck for all your best efforts. Server Racks, Kiosk Manufacturer.

    ReplyDelete