Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Special Scope Method with_options

Sometimes you might want to create a bundle of named routes, all of which pertain to the same controller. You can achieve this kind of batch creation of named routes via the with_options mapping method.

Let's say you've got the following named routes:

map.help '/help', :controller => "main", :action => "help"
map.contact '/contact', :controller => "main", :action => "contact"
map.about '/about', :controller => "main", :action => "about"

You can consolidate these three named routes like this:

map.with_options :controller => "main" do |main|
  main.help '/help', :action => "help"
  main.contact '/contact', :action => "contact"
  main.about '/about', :action => "about"

The three inner calls create named routes that are scoped—constrained—to use "main" as the value for the :controller parameter, so you don't have to write it three times.

Note that those inner calls use main, not map, as their receiver. After the scope is set, map calls upon the nested mapper object, main, to do the heavy lifting.

  • + Share This
  • 🔖 Save To Your Account