I am a Sr. Software Developer at Oracle Cloud. The opinions expressed here are my own and not necessarily those of my employer.
Rails and static content
Often in our applications we need to add pages with fairly static content (FAQ, About Us, etc). We could implement a full blown CMS or we could create a few HTML/ERB files. Let’s explore different approaches.
Template and controller
First we create home/about
template and controller.
Let’s do a quick perf test using wrk. ./wrk -d30s http://localhost:3000/home/about
gives us Requests/sec: 71.21
Fragment caching
Now we implement caching to speed up page loading. To enable Rails view caching we update development.rb or production.rb.
Add cache
block to app/views/home/about.html.erb
Data will be cached like this:
{"db":0,"key":"cache_ns:views/localhost:3000/home/about/
26b9257e71f9836c872a85c2d2f8359c","ttl":591,"type":"string","value":"...","size":17}
Running same perf test as before gives us Requests/sec: 66.16
which is slower.
High Voltage gem
high_voltage is a Rails engine for creating static pages. We can add cache
block to these files same as before.
{"db":0,"key":"cache_ns:views/localhost:3000/pages/products/
79fa0ff0d0bfcd1ab0b3b85a27f3c3bc","ttl":590,"type":"string","value":"...","size":29}
We can create folder/subfolder structure and apply caching to it.
{"db":0,"key":"cache_ns:views/localhost:3000/pages/products/product1/
712c98b51df8e161a1a89c8b56a636ac","ttl":597,"type":"string","value":"...","size":29}
Without caching running ./wrk -d30s http://localhost:3000/pages/products
gives us Requests/sec: 73.55
. With caching enabled we get Requests/sec: 66.78
.
Applying caching to such static files actually slows things down a little bit. If our pages had rich CSS or pulled data from DB then caching would likely speed things up.
HTML files
Another option is to simply put HTML/CSS/JS into public folder.
./wrk -d30s http://localhost:3000/about.html
gives us Requests/sec: 56277.05
. MUCH faster.
Static site generators
For more complex docs (such as technical documentation) we can integrate a static site generator like middleman or jekyll into our Rails app. Middleman gives us tools similar to Rails (helpers, partials, layouts) to speed up our development.
Add middleman
to Gemfile and run middleman init content
from app root. It will create content
subfolder. We want to output static HTML to public/content subfolder to serve via our webserver.
Running perf test ./wrk -d30s http://localhost:3000/content
gives us Requests/sec: 9936.43
. Slower than plain about.html page but now our page is much richer with CSS / JS.
After we deploy the application we need to run cd content && middleman build
via a post deploy hook on production server. Read middleman documentation for how to implement various features it supports.