Rack: One File Web Page With This Application

Reading Time: 2 minutes

There are times when you need to quickly create small Ruby web
applications. You can do that in many different ways like, creating a
Rails, Sinatra or Rack application.

I like this application, it gives you more than enough tools to build a web page, and
allows you to have full control of the components that you employ to
build it.

In this article I'll show some examples about how to create simple one page
Rack web applications.

For a bigger overview about this application, look at this article:
Rack Basics - A Rack Introduction.

Also remember, a middleware is nothing more than another
application, and, Rack middlewares can be stacked up in order to compose
bigger systems.

Examples source code

You can download and run the examples by following the next steps:

  git clone git://gist.github.com/935008.git gist-935008
  cd gist-935008
  gem install bundler && bundle install

Hello world

Let's start by building a simple hello world example, save the following
code as hello.ru:

Now, run the hello.ru app with:

  rackup hello.ru

Optionally you may specify what port you want your application to run
at:

  rackup hello.ru -p 8080

And then, go to http://localhost:9292/ or
http://localhost:8080/ (depending on what port
you specified), so you can see your app alive.

Creating an application in this way, requires you to manually specify the
headers, just as I did when I added the Content-Length and
Content-Type headers. Also, this can be accomplished in a simpler way
by using the Rack::ContentLength and Rack::ContentType middlewares:

OK, now let's add ERB rendering to this example.

Now, run the script again. You should see the Hello World message.

In order to show one last example let's write our view using
HAML, and passing variables to the view:

Run the script again. You should see the Hello World message.

That's it, you've seen how to create web pages by simply using
Rack, no frameworks, just Rack.

Thank you for your reading.

Know more about us!

0 Shares:
You May Also Like
Read More

Customize Solidus mailers

Reading Time: 2 minutes Solidus has a set of mailers which notify some actions such as confirmation of an order, notification when a…