Rutas de página estáticas de rieles vs: restricciones => {: url => /.+/} - pros y contras

I'm creating Page admin setup. Pages may include sub pages and I have a bunch of functionality to create the trailing url strings. Anyways, just wondering what the pros and cons here is. Speed-wise or anything I didn't really consider (aside maybe a bit more/less flexibility with other route matching):

Option 1 -- Match everything to pages:

get ':url' => 'pages#show', :constraints => { :url => /.+/ }
# with @page = Page.find_by_url("/"+params[:url]) in my controller

Option 2 -- Statically map routes to pages, and reload routes after each save

if Page.table_exists? # Otherwise on rake db:migrate this file will be called and throw an error
  Page.all.each do |page|
    match page.url, :controller => 'pages', :action => 'show', :page_id => page.id
  end
end
# Then after pages save it calls MyApp::Application.reload_routes!

Either way may work just as well.. just curious.

preguntado el 09 de marzo de 12 a las 22:03

2 Respuestas

Option-1 is superior and will actually work properly regardless of your deployment environment, Option-2 will fail in any non-trivial deployment.

Suppose you have two web server processes, P1 y P2; they may be on the same machine, separate machines, or perhaps in separate VMs on the same machine. Suppose some saves a new page that just happens to go to P1; entonces P1 will update the database (a shared resource between P1 y P2) and rebuild its routing table. But now P1 has the correct routing information but P2 is stuck with the old one because no one told it that something had changed.

You could set up some polling or broadcast system but that would just be a bunch of pointless complexity when Option-1 will work just fine as-is.

respondido 10 mar '12, 03:03

Yeah good point. I wouldn't have done that. But yeah Option 1 uses less dependency and quite a bit simpler. I suppose speed may be the other thing.. but I'm sure it's just as quick.. finding an id vs a url. - Wejrowski

You can use routes constraints:

 get ':url' => 'pages#show', :constraints => lambda {|request| Page.all.map(&:url).include?(request.path[1..-1]) }

Can yet to use a "catch all" to "page not found"

get '*not_found' => 'page#not_found'

http://guides.rubyonrails.org/routing.html#advanced-constraints

respondido 02 nov., 12:23

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.