Building your own framework with Rack and Ruby sounds super complicated, but its
suprisingly easy to get off the ground with just a few lines of code. Granted,
this isn't going to be the next rails competitor, but hopefully in the process
we can learn the basics of rack and expand our knowledge of web requests. I can't
promise this architecture is going to handle millions of requests, but I can say
that it WILL be able to handle at least YOUR request.
First things first, lets build a gemfile out so we can use bundler with our
project.
# Gemfile
source "http://rubygems.org"
ruby '2.0.0'
gem 'rack', '~> 1.5.2'
Don't forget to bundle after you save the Gemfile!
Notice we're going to use Ruby 2.0 for this because its super fast and hip. So
lets dive into the basics. Rack is very simple. Give it an object, it will call
the "call" method on that object and pass it information about the web request.
The return of that method should be an array with information about the response.
Thats all there is to it. Simple huh? Ok lets build a simple class to handle this.
Open up a file called request_controller.rb and insert the following lines.
class RequestController
def call(env)
[200, {}, ["Hello World"]]
end
end
So lets examine our response. The first index of the array should contain the
response code for the response. In this case we're sending a 200 ok back, but we
could send anything in the HTTP spec (404, 500, 301, etc). The second index of
the array should contain a hash with header information in it. In this case we
aren't sending any headers back. The third index in the array is another array
containing the response. Keep in mind that at its very core, Rails is responding
in a very similar fasion to this. There is a lot of power in these few lines of
code.
This class alone doesn't do anything for us though. We need to tell rack about
this class, and you do that in a rack up file. We'll build one now, open up a
file named brain_rack.ru and insert the following:
#!/usr/bin/env ruby
require 'rack'
load 'request_controller.rb'
Rack::Handler::WEBrick.run(
RequestController.new,
:Port => 9000
)
This is fairly straight forward if you're familar with ruby. The first 3 lines
are the shebang, and requiring the various files we need. The last lines
instantiate our RequestHandler class and tell Rack that we want to use port
9000. In this case we're using WEBrick which is built into ruby.
Now lets run the thing:
rackup brain_rack.ru
and the output should be
[2013-04-29 22:50:59] INFO WEBrick 1.3.1
[2013-04-29 22:50:59] INFO ruby 2.0.0 (2013-02-24) [x86_64-darwin12.3.0]
[2013-04-29 22:50:59] INFO WEBrick::HTTPServer#start: pid=9931 port=9000
Now going to localhost:9000 in a browser should give the output Hello World! We
built our first simple rack app. Stay tuned for the next parts of the series
and we'll flesh out our framework more.