Home > Articles > Programming > Ruby

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

This chapter is from the book

Globbing Key-Value Pairs

Route globbing might provide the basis for a general mechanism for fielding queries about items up for auction. Let's say you devise a URI scheme that takes the following form:

http://localhost:3000/items/field1/value1/field2/value2/...

Making requests in this way will return a list of all items whose fields match the values, based on an unlimited set of pairs in the URL.

In other words, http://localhost:3000/items/year/1939/medium/wood would generate a list of all wood items made in 1939.

The route that would accomplish this would be:

map.connect 'items/*specs', :controller => "items", :action => "specify"

Of course, you'll have to write a specify action like the one in Listing 3.2 to support this route.

Listing 3.2. The specify Action

def specify
  @items = Item.find(:all, :conditions => Hash[params[:specs]])
  if @items.any?
    render :action => "index"
  else
    flash[:error] = "Can't find items with those properties"
    redirect_to :action => "index"
  end
end

How about that square brackets class method on Hash, eh? It converts a one-dimensional array of key/value pairs into a hash! Further proof that in-depth knowledge of Ruby is a prerequisite for becoming an expert Rails developer.

Next stop: Named routes, a way to encapsulate your route logic in made-to-order helper methods.

  • + Share This
  • 🔖 Save To Your Account