Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Forked from chrislloyd/page.rb
Created February 16, 2009 00:17
Show Gist options
  • Save xaviershay/64917 to your computer and use it in GitHub Desktop.
Save xaviershay/64917 to your computer and use it in GitHub Desktop.
Refactor this code: URL Matching Edition
--
So I have Pages, in a nested set so that each page has parent. That allows me to have urls like:
/foo/bar
where the Page with permalink 'foo' has a child with the permalink 'bar'. In my routes.rb I have a general catch-all route as my last route.
map.page '/*tree', :controller => 'pages', :action => 'show'
and the show action pretty much just passes the params array to Page.find_by_params! method.
The code could have looked as simple as:
def self.find_from_params!(params)
find_by_permalink(params.last)
end
but I want each page to only have _one_ distinct url (i.e. when finding the page 'foo' it needs to check that it's parent is 'bar'.
The code above works, thought it is intentionally fucking ugly. Go forth and work your Ruby magic on it.
HINTS: Lambdas?
EDIT: Oh, also assume that each page's permalink is unique within it's siblings.
class Page
def self.parse_params(params, parent=nil)
return parent if params.empty?
# Exit condition: raises error if there are no permalinks
puts page = find_by_permalink_and_parent!(params.first, parent)
params.shift!
parse_params(params, page)
end
# Only collapsed this function
def self.find_by_permalink_and_parent!(permalink, parent)
first(:conditions => {:parent_id => parent, :permalink => permalink}) || ActiveRecord::RecordNotFound
end
def self.find_from_params!(params)
parse_params(params)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment