Rails as a Rack application
Rack provides a modular interface for developing web apps in Ruby. A
Rack::Handler connects webservers with Rack. By default it ships with handlers for Thin, WEBrick, FastCGI, CGI, SCGI and LiteSpeed. It also provides a handy
rackup commandline tool, which internally starts a Rack::Server.
Any object that responds to a
call function and takes an env hash as parameter, returning an Array with the http response code, hash of headers, and a response body that can respond to
For example the below instance of the class
RunMe. You can run this with a Rack Handler.
Save all of this in a server.rb and run it with
rackup command line tool can be used, in which case you can forego the explicit use of the WEBrick handler.
rackup internally calls
Running the rack server in Rails
rails server is called the
start method of
Rails::Server is called.
Rails::Server inherits from
Rails::Application is an class with a
call function and has all the properties of . So if we define a class that inherits from
Rails::Application we can serve it with
So lets create a simple
Rails::Application. Create a file named
config.ru as follows:
This just prints ‘Hello World’. For a more useful experiment, you can define a controller and render a template.
Lets create a
PagesController that renders some html inline.
Tada! This right here, is a Rails application in a single file, with just 20 lines of Ruby.
For a more complex example, let split out the files. Its not single file anymore!
Lets split out the
config.ru file into application.rb (which handles the Rails part) and config.ru (which handles the
run). And connect to a database(sqlite3) and render a template view file. So now we have a
views folder with
users/index.html.erb in it.
The code is as follows: You can use this to test out features, or to log a bug report etc.
All the source code for this post is available at HASH32 Github Repo.
Although this is just a few files, it loads a lot of stuff internally. It’s definitely possible to remove some things. I’ll explore on how to render a json API and trim down the stack, but that’s for another post.
Subscribe to our Newsletter
Get stories like the directly to your inbox once every two weeks.
Tips and tricks, news about tech tools, recent blog entries and exclusive email only stories.