If I am caching an rss response like so:
<% cache do %>
<%= fetch_rss(http://ex开发者_JAVA技巧ample.org) %>
<% end %>
how could I prevent it from caching if the rss doesn't return correctly? i.e. if the fetch_rss returns an exception or returns 'Not Found'
Tricky.
Couple of ideas.
You could pull the fetch_rss call up into your controller. The cache is actually just a hash that is available to your app. So this requires a little bit of extra legwork, but is probably the most straight forward approach. Explicitly check the cache, and either call fetch_rss if the cache is stale or pull the rss value from the cache and pass into the view to render as normal.
Alternatively, you might be able to get your fetch to throw an error, and then wrap in an exception handler. If there is an exception, you would catch and call expire_fragment.
Move the fetch_rss
method into your controller where it belongs, then handle known exceptions:
def index
begin
@rss = fetch_rss
# Caching can be done here ...
rescue InvalidRssError, NotFoundError => e
# ...
end
end
As you can see, assuming there are no exceptions when fetching the RSS, you won't need to expire or otherwise change the cache unless you have a successful pull.
精彩评论