Simple static pages in ruby on rails.
— April 2, 2008 at 09:38 PDT
Simple things should be simple, complex things should be possible. — Alan Kay
Here’s a tiny little tip for handling those boiler-plate pages that aren’t part of your app’s functionality but you usually need anyway. It’s good for setting up about, contact, copyright, etc. You can always throw those pages into /public as static html files, but if you want them to get styled with layouts, they need to be rendered as actions. This is a way to do that simply. It’s not rocket science, but I haven’t done a noob post in ages and I’m getting over a cold and I haven’t posted in too long so gimme a break.
Say you want to have a simple landing page and a few typical boiler-plate pages. Let’s start with the routes.
In config/routes.rb
map.root :controller => 'home'
map.home ':page', :controller => 'home', :action => 'show', :page => /about|contact/
In app/controllers/home_controller.rb
def index
# render the landing page
end
def show
render :action => params[:page]
end
Throw your about.html or about.html.erb and other pages into app/views/home and you’re good to go. If you’ve set up page caching, this won’t even slow your app down.
The :page => /.../
bit in the route constrains it to match only those specific urls. If you want, you can change that to a constant, like HomeController::
PAGES, so it’s easier to manage.
If you want to link to those pages, you can use the route helper methods, home_path
and home_url
link_to 'About', home_path('about')
You could always unroll the routes and have a separate route for each page, but I find this way a bit drier. But if you’d rather have a specific named route helper for each page, that’s an okay way to go. Either way, you get to use layouts in your pages, and have a nice simple way to get them rendered.