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 ruby server.rb .

The rackup command line tool can be used, in which case you can forego the explicit use of the WEBrick handler. rackup internally calls Rack::Server.start

Running the Rails Application on Rack

When rails server is called the start method of Rails::Server is called. Rails::Server inherits from Rack::Server .

Rails::Application is an class with a call function and has all the properties of [1]. 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.

This right here, is a Rails application in a single file, with just 16 lines of Ruby. Well pretty small, huh! If you need to build something useful with this, it will be well beyond 16 lines of course, but you can fit all of it in a single file.

You can use this for running specialized applications on Rack, with the features of Rails, and you can pick and choose which ones. Load only the libraries and middlewares you use in Rails and run the app on Rack.

You can split up the views to a separate folder, models into separate files and use require_relative to use them. Or organize folders based on functionality. Or bring a folder structure that fit your needs.

Sample Rails application on Rack folder structure.

You can find the source for this article, and more examples in the https://github.com/HASH32/rails-and-rack repository.

References

Read the official Ruby on Rails guide on Rails on Rack.

Watch this talk by José Valim — You’ve got a Sinatra on your Rails

PS: This article was originally posted in HASH32 Engineering Blog.