Using url_for and expire_page in console and runner

December 12, 2007

I implemented page caching in a recent Rails project along with the necessary cache sweeper to keep everything nice and tidy. However, now I needed a way to expire pages outside of the web application — that is, from script/console and script/runner.

It had been my understanding that this was going to be difficult as expire_page and url_for need the web request framework in order to run. I found maiha's post on Url generations in script/console that had the information I needed between the post itself and the comments.

I'm writing this primarily in the hopes that Google will pick it up and make finding it easier for the next person.

Via script/console

Console automatically loads up rails/railties/lib/console_app.rb. That file provided the app method. That method sets up a fake web request.

>> app.url_for(:controller => 'foo', :action => 'bar')
=> ''
>> app.url_for(:controller => 'foo', :action => 'bar', :only_path => true)
=> '/foo/bar'
>>! ''
=> ''
>> app.url_for(:controller => 'foo', :action => 'bar')
=> ''

To expire a page you would do:

ActionController::Base.expire_page(app.url_for(:controller => 'foo',
                                               :action => 'bar',
                                               :only_path => true))

Via script/runner

Runner uses the same code as Console, but you first need to load console_app.rb. This can be done by the following statement placed at the top of the file to be run:

require 'lib/console_app'