Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

178 | Chapter 6: Performance


Action caching is triggered by thecaches_actionmethod. Here’s an example that
only allows a page to be viewed on Tuesdays:


class UserController < ApplicationController
before_filter :tuesday?, :only => :happy_tuesday
caches_action :happy_tuesday

def happy_tuesday
render :text => "Happy Tuesday!"
end

protected

def tuesday?
Time.now.wday == 2
end
end

Action-cached pages are expired with theexpire_actionmethod, which is again best
called from a cache sweeper. Alternatively, since action caching is implemented on
top of fragment caching, you can use theexpire_fragmentmethod to expire one or
many actions at once. You can even use a regular expression to expire all cached
instances of one action (or all actions if you like).


Fragment caching


When the preceding options fail, fragment caching can help. Fragment caching is
the most flexible, but least helpful, option. It is designed to store small fragments of
the page, but it makes no assumptions about your data. You can store HTML frag-
ments, XML, JSON, or even images in the fragment cache.


Manual access to the fragment cache uses theread_fragment,write_fragment, and
expire_fragmentmethods. This example caches barcode images as they are gener-
ated, to avoid generating them every time they are needed:


# /barcode/generate/12345
class BarcodeController < ApplicationController
def generate
text = params[:id]

# Retrieve barcode from fragment cache or generate it ourselves
bc = read_fragment("barcode/generate/#{text}") ||
write_fragment("barcode/generate/#{text}", Code39.to_jpeg(text))

# Write the response to the client
send_data bc, :type => 'image/jpeg', :disposition => 'inline'
end
end
Free download pdf