Dealing with static pages in Rails will almost always result in creating a special controller with empty actions that just render out some template. This task is so common that it is perfect to extract it out into a Rails engine.
ThoughtBot, the company behind the
paperclip gem has done just that.
high_voltage is a gem that handles the routes for you and provides nice helper methods.
Installation of the gem is straight forward. Add the gem to your Gemfile and run the bundle command to install the gem.
The High Voltage gem expects all static files to reside in a
pages directory under
app/views. We will start off by creating this directory and a file to represend the about page of our rails application.
mkdir app/views/pages touch app/views/pages/about.html.haml
%h2 About Us %p This is a awesome Rails application!
High Voltage will now provide URL helpers that you can use throughout your application. We can add an "About Us" link to the applications layout by using the
page_path helper method and passing it the name of the of the page.
... %nav %ul %li= link_to 'About Us', page_path('about') ...
Sometimes serving static pages is not enough. You might want to add authentication to the static page or need to render a different layout. High Voltage allows you to extend its
rails generate controller pages
You will have to add the controller to your routes:
Now by default every controller in Rails extends the
ApplicationController, in order to still use High Voltage we need to change this to
HighVoltage::PagesController. We can then start adding some custom behaviour to the controller like adding authentication (e.g. via devise).
class PagesController < HighVoltage::PagesController before_filter :authenticate_user! end
I hope you found this article useful.
HighVoltage at Github