Ruby on Rails static site generator
June 17, 2023
How to generate a static website from a Ruby on Rails project. This is how I managed to publish this website 😉
Based on this post
Rakefile
Add a namespace "static" with the two commands "generate" and "server" (rake static:generate
and rake static:server
):
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:9000/. Press CTRL+C to exit.'
`python3 -m http.server 9000`
end
end
end
.gitignore
Add the "out" folder to the .gitignore file:
/out/*
routes.rb
All routes that would be presented on the static website should have a .html
format, for example:
get "rails-static-pages", to: "posts#static", :defaults => { :format => 'html' }
Also, all links in the *.erb
files show have a .html
in the end, for example:
<%= link_to "Timeline", "timeline.html" %>
Ready to generate
Now start a rails server
rails s
And run this command in a separate tab
rake static:generate
Test the website with an HTTP server
rake static:server
GitHub Pages
Now you can upload the contents of the "out" folder to GitHub and publish for free on GitHub Pages.
Details and instructions on how to do this can be found here: pages.github.com