Posts Tagged ‘caching’

How to Use Pretty URLs with Rails will_paginate Plugin

Posted 17 Jun 2009 — by admin
Category Ruby on Rails

The will_paginate plugin for Rails uses a key/value assignment like ?page=2, rather than the pretty url formats such as /page/2 … This is because url generation and mapping are handled by the routes.rb file. You’ll need to modify the file so that rails knows what to do with request that match the pattern. Make sure to put the custom (map.connect) route before the normal restful routes (map.resources)

map.connect '/topics/:id/page/:page', :controller => 'topics', :action => 'show'
map.resources :topics

Internally will_paginate uses the url_for method so Rails will now know how to construct your urls in a pretty way. I got most of this info from this discusson http://groups.google.com/group/will_paginate/browse_thread/thread/d0142b512cfca9d5?pli=1

There is nothing wrong leaving the default behavior alone and looking at the ‘ugly’ key/value pairs in the address bar. However, if you take advantage of page caching in rails, you’ll need to do this anyway. Page caching in rails ignore extra parameters, any info before/after the “?” and “&” symbols. There will be no difference from /topics/2?page=1 and /topics/2?page=100 in your cache. And since most likely the content will be very different on these two pages, you’ll need to have pretty urls so that page caching will save topics/2/page/1.html and topics/2/page/100.html as two different resources!

Rails: Expiring a cached page with namespaces and sweepers

Posted 31 May 2009 — by admin
Category Ruby on Rails

I’ve got some pages that are cached using their permalinks on the filesystem, such as http://example.com/about-us.html which will need to map to RAILS_ROOT/public/about-us.html … The issue I have is that I use a namespace for the admin area and the controllers in the namespace are responsible for expiring the cached pages, i.e., when the resources are updated by an admin.

Check out Rails Envy for a great tutorial for getting page caching set up: http://www.railsenvy.com/2007/2/28/rails-caching-tutorial

So what I want to do is expire the pages from inside my namespace. To accomplish this I need to use the pages route in my sweeper class.

class PageSweeper < ActionController::Caching::Sweeper
  #... after_save, after_destroy... we'll exprire the cache
  def expire_cache_for(record)
    #permalink rather than record id like /213.html
    expire_page(pages_path(record.permalink))
  end
end

Since I'm using a permalink to cache the page, I need to expire it with the permalink too.