How to use Ruby in place of PHP

by James

PHP has a great reputation as a hackers’ language, a tool for putting together websites with minimum fuss. It’s pretty easy to add new features to PHP-based websites too, as you scale. But what if you’re a Ruby fanatic, or just plain lazy, like me?

Ruby doesn’t have the built-in server-side support that PHP has (PHP code will run automatically on most hosts; Ruby code won’t) — but it’s still very easy to code a website using Ruby, and I think the long-term benefits in terms of maintenance and cool code tricks are definitely worth the effort.

Yet another ‘Hello World!’ example

Ruby’s CGI class will be the base of any attempt to serve web content with Ruby. It provides an easy way to access server environment variable and request headers, and just as importantly CGI objects allow you to output HTML (or anything else) very easily:

[ruby]
require ‘cgi’

CGI.new.out(‘text/html’) { "Hello world!" }
[/ruby]

Simple enough for you? We create a new CGI object and call its out method with two arguments: the type of the content we’re sending, and a block which returns the content itself. Here I’m sending HTML, but I could also use ‘text/plain’, ‘text/xml’, etc — depending on what content I was sending.

The out method also lets you do various clever things to create HTML elements: check out the CGI documentation for more details.

Add more code and mix well

I can send textual content, but what if I want to get more involved and start putting Ruby code into HTML files, like I could with PHP or Rails? ERB to the rescue:

[ruby]
require ‘cgi’
require ‘erb’

CGI.new.out(‘text/html’) do
# everything between the <% %> tags is evaluated as ruby code
ERB.new("<p>1 + 1 = <%= 1 + 1 %></p>").result
end
[/ruby]

That should output:

[html]
<p>1 + 1 = 2</p>
[/html]

From this point, it’s easy to build up more complicated ERB templates and mix complex Ruby methods and their results into your HTML. Before you know it, PHP is long forgotten and your website is running on Ruby!

Brining it all back home

There are a few more things you need to know before you can really use these techniques to get a webpage up and running: I hope to post a follow up article soon to run through deploying, creating helper methods, separating layout and content, and more.

For now, though, read the CGI docs and play around — it’s fun, honest :-)

My random password generator is a ruby-powered web page: check it out for an example of what Ruby can do.