Clean up Routes #with_options
Monday, October 20th, 2008 · 0 comments
Say there are a couple static pages in an application, and we have a StaticController with a few methods specifically for rendering views, such as about or privacy.
# app/controllers/static_controller.rb
class StaticController < ApplicationController
def about
# render about.html.erb
end
def privacy
# render privacy.html.erb
end
end
map.resources :static wouldn't work, because it's not exactly a Rails resource (add, edit, update, new etc.). Also it would be nice to have them as top level directories (domain.com/about). So, the solution (one of them at least) would be to map.with_options!
Here's the code.
# config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.with_options :controller => "static" do |static|
static.about "/about", :action => "about"
static.privacy "/privacy", :action => "privacy"
end
end
To break it down, by using with_options and :controller => "static" the code is simply adding :controller => "static" to each of the routes inside the block. It's the equivalent of:
map.about "/about", :controller => "static", :action => "about"
map.privacy "/privacy", :controller => "static", :action => "privacy"
Just another random snippet, hopefully it's useful to someone out there.
