Damian Nowak is a CEO at Virtkick. He's a Ruby coder, an Arch Linux hacker, and drinks good beer.

Ruby on Rails - a static site generatorFebruary 2011

This post has been originally posted at blog.atlashost.eu, which I decided to discontinue.
Please visit atlashost.eu to get familiar with AtlasHost.

Creating a website with Ruby on Rails is just fun. You get lots of things out of the box so that you don’t have to reinvent the wheel. The only thing you have to do is to focus on creating the website. I use Rails both for static and dynamic sites. Hold on, what do you mean by “static” if every Rails application is dynamic? Just consider static every website that can be generated once and served forever.

Once you have a static website written in Ruby on Rails, you get two options. Either find a relatively expensive Rails hosting or generate static HTMLs and host it anywhere for $5 a year or so. If you like the second option, here’s a quick solution for generating HTMLs from Rails application. Some parts of code come from etd’s post.

Prerequisites

You need wget, rsync and Python besides your Ruby on Rails.

Rakefile

namespace :static do
  desc 'Generate static site in ./out/ directory'
  task :generate do
    Dir.mkdir 'out' unless File.exist? 'out'
    Dir.chdir 'out' do
      `wget -mnH http://localhost:3000/`
    end
    `rsync -ruv --exclude=.svn/ public/ out/`
  end

  desc 'Run tiny HTTP server from ./out/ directory'
  task :server do
    Dir.chdir 'out' do
      puts 'Started HTTP server at http://localhost:8000/. Press CTRL+C to exit.'
      `python -m SimpleHTTPServer`
    end
  end
end

config/environment.rb

Rails adds a timestamp like /default.css?1291255529 to all static files. I don’t want such ugly filenames in my generated static website so I append this to config/environment.rb:

# Do not include timestamp in static files
ENV['RAILS_ASSET_ID'] = ''

We are done now

You must first start Rails server to generate the website to out/ directory.

$ rails server
$ rake static:generate

You can test the website with a tiny HTTP server.

$ rake static:server
$ x-www-browser 'http://localhost:8000/'
Damian Nowak
CEO & Ruby Developer